method_name
stringlengths
1
78
method_body
stringlengths
3
9.66k
full_code
stringlengths
31
10.7k
docstring
stringlengths
4
4.74k
_get_get_session_history
chat_history_store = store if store is not None else {} def get_session_history(session_id: str, **kwargs: Any) ->ChatMessageHistory: if session_id not in chat_history_store: chat_history_store[session_id] = ChatMessageHistory() return chat_history_store[session_id] return get_session_history
def _get_get_session_history(*, store: Optional[Dict[str, Any]]=None ) ->Callable[..., ChatMessageHistory]: chat_history_store = store if store is not None else {} def get_session_history(session_id: str, **kwargs: Any ) ->ChatMessageHistory: if session_id not in chat_history_store: ...
null
load
"""Load Documents from URLs.""" return list(self.lazy_load())
def load(self) ->List[Document]: """Load Documents from URLs.""" return list(self.lazy_load())
Load Documents from URLs.
buffer_as_str
"""Exposes the buffer as a string in case return_messages is True.""" messages = self.chat_memory.messages[-self.k * 2:] if self.k > 0 else [] return get_buffer_string(messages, human_prefix=self.human_prefix, ai_prefix=self.ai_prefix)
@property def buffer_as_str(self) ->str: """Exposes the buffer as a string in case return_messages is True.""" messages = self.chat_memory.messages[-self.k * 2:] if self.k > 0 else [] return get_buffer_string(messages, human_prefix=self.human_prefix, ai_prefix=self.ai_prefix)
Exposes the buffer as a string in case return_messages is True.
_clean_data
from bs4 import BeautifulSoup soup = BeautifulSoup(data, 'html.parser', **self.bs_kwargs) html_tags = [('div', {'role': 'main'}), ('main', {'id': 'main-content'})] if self.custom_html_tag is not None: html_tags.append(self.custom_html_tag) element = None for tag, attrs in html_tags[::-1]: element = soup.find(ta...
def _clean_data(self, data: str) ->str: from bs4 import BeautifulSoup soup = BeautifulSoup(data, 'html.parser', **self.bs_kwargs) html_tags = [('div', {'role': 'main'}), ('main', {'id': 'main-content'})] if self.custom_html_tag is not None: html_tags.append(self.custom_html_tag) element = No...
null
create_schema
"""Create the database schema for the record manager."""
@abstractmethod def create_schema(self) ->None: """Create the database schema for the record manager."""
Create the database schema for the record manager.
_import_azure_cognitive_services_AzureCogsFormRecognizerTool
from langchain_community.tools.azure_cognitive_services import AzureCogsFormRecognizerTool return AzureCogsFormRecognizerTool
def _import_azure_cognitive_services_AzureCogsFormRecognizerTool() ->Any: from langchain_community.tools.azure_cognitive_services import AzureCogsFormRecognizerTool return AzureCogsFormRecognizerTool
null
similarity_search_with_score
"""The most k similar documents and scores of the specified query. Args: embeddings: embedding vector of the query. k: The k most similar documents to the text query. min_score: the score of similar documents to the text query Returns: The k most similar d...
def similarity_search_with_score(self, query: str, k: int=DEFAULT_TOPN, ** kwargs: Any) ->List[Tuple[Document, float]]: """The most k similar documents and scores of the specified query. Args: embeddings: embedding vector of the query. k: The k most similar documents to the text ...
The most k similar documents and scores of the specified query. Args: embeddings: embedding vector of the query. k: The k most similar documents to the text query. min_score: the score of similar documents to the text query Returns: The k most similar documents to the specified text query. 0 is diss...
is_lc_serializable
return True
@classmethod def is_lc_serializable(cls) ->bool: return True
null
plan
"""Given input, decide what to do."""
@abstractmethod def plan(self, inputs: dict, callbacks: Callbacks=None, **kwargs: Any) ->Plan: """Given input, decide what to do."""
Given input, decide what to do.
eval_project_name
return f'lcp integration tests - {str(uuid4())[-8:]}'
@pytest.fixture def eval_project_name() ->str: return f'lcp integration tests - {str(uuid4())[-8:]}'
null
create_sync_playwright_browser
""" Create a playwright browser. Args: headless: Whether to run the browser in headless mode. Defaults to True. args: arguments to pass to browser.chromium.launch Returns: SyncBrowser: The playwright browser. """ from playwright.sync_api import sync_playwright browser = sync_pl...
def create_sync_playwright_browser(headless: bool=True, args: Optional[List [str]]=None) ->SyncBrowser: """ Create a playwright browser. Args: headless: Whether to run the browser in headless mode. Defaults to True. args: arguments to pass to browser.chromium.launch Returns: ...
Create a playwright browser. Args: headless: Whether to run the browser in headless mode. Defaults to True. args: arguments to pass to browser.chromium.launch Returns: SyncBrowser: The playwright browser.
_import_spark_sql_tool_QuerySparkSQLTool
from langchain_community.tools.spark_sql.tool import QuerySparkSQLTool return QuerySparkSQLTool
def _import_spark_sql_tool_QuerySparkSQLTool() ->Any: from langchain_community.tools.spark_sql.tool import QuerySparkSQLTool return QuerySparkSQLTool
null
test_parse_scores
result = output_parser.parse_folder(answer) assert result['answer'] == 'foo bar answer.' score = int(result['score']) assert score == 80
@pytest.mark.parametrize('answer', (GOOD_SCORE, SCORE_WITH_EXPLANATION)) def test_parse_scores(answer: str) ->None: result = output_parser.parse_folder(answer) assert result['answer'] == 'foo bar answer.' score = int(result['score']) assert score == 80
null
format_request_payload
prompt = ContentFormatterBase.escape_special_characters(prompt) request_payload = json.dumps({'inputs': {'input_string': [f'"{prompt}"']}, 'parameters': model_kwargs}) return str.encode(request_payload)
def format_request_payload(self, prompt: str, model_kwargs: Dict) ->bytes: prompt = ContentFormatterBase.escape_special_characters(prompt) request_payload = json.dumps({'inputs': {'input_string': [f'"{prompt}"' ]}, 'parameters': model_kwargs}) return str.encode(request_payload)
null
handle_event
"""Generic event handler for CallbackManager. Note: This function is used by langserve to handle events. Args: handlers: The list of handlers that will handle the event event_name: The name of the event (e.g., "on_llm_start") ignore_condition_name: Name of the attribute defined on hand...
def handle_event(handlers: List[BaseCallbackHandler], event_name: str, ignore_condition_name: Optional[str], *args: Any, **kwargs: Any) ->None: """Generic event handler for CallbackManager. Note: This function is used by langserve to handle events. Args: handlers: The list of handlers that wil...
Generic event handler for CallbackManager. Note: This function is used by langserve to handle events. Args: handlers: The list of handlers that will handle the event event_name: The name of the event (e.g., "on_llm_start") ignore_condition_name: Name of the attribute defined on handler that if Tru...
_default_params
params: Dict[str, Any] = {'gateway_uri': self.gateway_uri, 'route': self. route, **self.params.dict() if self.params else {}} return params
@property def _default_params(self) ->Dict[str, Any]: params: Dict[str, Any] = {'gateway_uri': self.gateway_uri, 'route': self.route, **self.params.dict() if self.params else {}} return params
null
ids
prefix = self.prefix + '/' if self.prefix else '' keys = self.key if isinstance(self.key, list) else [self.key] return [f'{CONTEXT_CONFIG_PREFIX}{prefix}{k}{CONTEXT_CONFIG_SUFFIX_GET}' for k in keys]
@property def ids(self) ->List[str]: prefix = self.prefix + '/' if self.prefix else '' keys = self.key if isinstance(self.key, list) else [self.key] return [f'{CONTEXT_CONFIG_PREFIX}{prefix}{k}{CONTEXT_CONFIG_SUFFIX_GET}' for k in keys]
null
top_parent
"""Get the parent of the top of the stack without popping it.""" return self.stack[-2] if len(self.stack) > 1 else None
def top_parent(self) ->Optional[Thought]: """Get the parent of the top of the stack without popping it.""" return self.stack[-2] if len(self.stack) > 1 else None
Get the parent of the top of the stack without popping it.
test_md_header_text_splitter_2
"""Test markdown splitter by header: Case 2.""" markdown_document = """# Foo ## Bar Hi this is Jim Hi this is Joe ### Boo Hi this is Lance ## Baz Hi this is Molly""" headers_to_split_on = [('#', 'Header 1'), ('##', 'Header 2'), ('###', 'Header 3')] markdown_splitter = MarkdownHeaderTextSplitter(hea...
def test_md_header_text_splitter_2() ->None: """Test markdown splitter by header: Case 2.""" markdown_document = """# Foo ## Bar Hi this is Jim Hi this is Joe ### Boo Hi this is Lance ## Baz Hi this is Molly""" headers_to_split_on = [('#', 'Header 1'), ('##', 'Header 2'), ('###', 'H...
Test markdown splitter by header: Case 2.
on_llm_end
"""Run when LLM ends running.""" self.metrics['step'] += 1 self.metrics['llm_ends'] += 1 self.metrics['ends'] += 1 llm_ends = self.metrics['llm_ends'] resp: Dict[str, Any] = {} resp.update({'action': 'on_llm_end'}) resp.update(flatten_dict(response.llm_output or {})) resp.update(self.metrics) self.mlflg.metrics(self.me...
def on_llm_end(self, response: LLMResult, **kwargs: Any) ->None: """Run when LLM ends running.""" self.metrics['step'] += 1 self.metrics['llm_ends'] += 1 self.metrics['ends'] += 1 llm_ends = self.metrics['llm_ends'] resp: Dict[str, Any] = {} resp.update({'action': 'on_llm_end'}) resp.upd...
Run when LLM ends running.
thread_target
nonlocal result_container new_loop = asyncio.new_event_loop() asyncio.set_event_loop(new_loop) try: result_container.append(new_loop.run_until_complete(self._arun(*args, **kwargs))) except Exception as e: result_container.append(e) finally: new_loop.close()
def thread_target() ->None: nonlocal result_container new_loop = asyncio.new_event_loop() asyncio.set_event_loop(new_loop) try: result_container.append(new_loop.run_until_complete(self._arun(* args, **kwargs))) except Exception as e: result_container.append(e) finally...
null
test_tracer_chain_run_on_error
"""Test tracer on a Chain run with an error.""" exception = Exception('test') uuid = uuid4() compare_run = Run(id=str(uuid), start_time=datetime.now(timezone.utc), end_time=datetime.now(timezone.utc), events=[{'name': 'start', 'time': datetime.now(timezone.utc)}, {'name': 'error', 'time': datetime.now( time...
@freeze_time('2023-01-01') def test_tracer_chain_run_on_error() ->None: """Test tracer on a Chain run with an error.""" exception = Exception('test') uuid = uuid4() compare_run = Run(id=str(uuid), start_time=datetime.now(timezone.utc), end_time=datetime.now(timezone.utc), events=[{'name': 'start...
Test tracer on a Chain run with an error.
test_chat_openai
"""Test AzureChatOpenAI wrapper.""" message = HumanMessage(content='Hello') response = llm([message]) assert isinstance(response, BaseMessage) assert isinstance(response.content, str)
def test_chat_openai(llm: AzureChatOpenAI) ->None: """Test AzureChatOpenAI wrapper.""" message = HumanMessage(content='Hello') response = llm([message]) assert isinstance(response, BaseMessage) assert isinstance(response.content, str)
Test AzureChatOpenAI wrapper.
process_threads
"""Process a list of thread into a list of documents.""" docs = [] for thread_id in thread_ids: doc = self.process_thread(thread_id, include_images, include_messages) if doc is not None: docs.append(doc) return docs
def process_threads(self, thread_ids: Sequence[str], include_images: bool, include_messages: bool) ->List[Document]: """Process a list of thread into a list of documents.""" docs = [] for thread_id in thread_ids: doc = self.process_thread(thread_id, include_images, include_messages) if d...
Process a list of thread into a list of documents.
test_visit_structured_query_operation
query = 'What is the capital of France?' op = Operation(operator=Operator.OR, arguments=[Comparison(comparator= Comparator.EQ, attribute='foo', value=2), Comparison(comparator= Comparator.CONTAIN, attribute='bar', value='baz')]) structured_query = StructuredQuery(query=query, filter=op) expected_filter = (Redis...
def test_visit_structured_query_operation(translator: RedisTranslator) ->None: query = 'What is the capital of France?' op = Operation(operator=Operator.OR, arguments=[Comparison(comparator= Comparator.EQ, attribute='foo', value=2), Comparison(comparator= Comparator.CONTAIN, attribute='bar', val...
null
_get_relevant_documents
ctxs = self.client.query(query=query, num_context=self.num_contexts) docs = [] for ctx in ctxs: page_content = ctx.pop('chunk_embed_text', None) if page_content is None: continue docs.append(Document(page_content=page_content, metadata={**ctx})) return docs
def _get_relevant_documents(self, query: str, *, run_manager: CallbackManagerForRetrieverRun) ->List[Document]: ctxs = self.client.query(query=query, num_context=self.num_contexts) docs = [] for ctx in ctxs: page_content = ctx.pop('chunk_embed_text', None) if page_content is None: ...
null
_load_document_from_bytes
"""Return a document from a bytes representation.""" obj = loads(serialized.decode('utf-8')) if not isinstance(obj, Document): raise TypeError(f'Expected a Document instance. Got {type(obj)}') return obj
def _load_document_from_bytes(serialized: bytes) ->Document: """Return a document from a bytes representation.""" obj = loads(serialized.decode('utf-8')) if not isinstance(obj, Document): raise TypeError(f'Expected a Document instance. Got {type(obj)}') return obj
Return a document from a bytes representation.
_prompt_type
"""Return the prompt type key.""" raise NotImplementedError
@property def _prompt_type(self) ->str: """Return the prompt type key.""" raise NotImplementedError
Return the prompt type key.
_stream_generate
""" Args: prompt: The prompt to use for generation. model: The model used for generation. stop: Optional list of stop words to use when generating. generate_config: Optional dictionary for the configuration used for generation. Yields: ...
def _stream_generate(self, model: Union['RESTfulGenerateModelHandle', 'RESTfulChatModelHandle'], prompt: str, run_manager: Optional[ CallbackManagerForLLMRun]=None, generate_config: Optional[ 'LlamaCppGenerateConfig']=None) ->Generator[str, None, None]: """ Args: prompt: The prompt t...
Args: prompt: The prompt to use for generation. model: The model used for generation. stop: Optional list of stop words to use when generating. generate_config: Optional dictionary for the configuration used for generation. Yields: A string token.
ignore_llm
"""Whether to ignore LLM callbacks.""" return self.ignore_llm_
@property def ignore_llm(self) ->bool: """Whether to ignore LLM callbacks.""" return self.ignore_llm_
Whether to ignore LLM callbacks.
_default_params
"""Return default params.""" return {'host': self.host, 'endpoint_name': self.endpoint_name, 'cluster_id': self.cluster_id, 'cluster_driver_port': self. cluster_driver_port, 'databricks_uri': self.databricks_uri, 'model_kwargs': self.model_kwargs, 'temperature': self.temperature, 'n': self.n, 'stop': se...
@property def _default_params(self) ->Dict[str, Any]: """Return default params.""" return {'host': self.host, 'endpoint_name': self.endpoint_name, 'cluster_id': self.cluster_id, 'cluster_driver_port': self. cluster_driver_port, 'databricks_uri': self.databricks_uri, 'model_kwargs': self....
Return default params.
test_extract_html
bs_transformer = BeautifulSoupTransformer() paragraphs_html = ( '<html>Begin of html tag<h1>Header</h1><p>First paragraph.</p>Middle of html tag<p>Second paragraph.</p>End of html tag</html>' ) documents = [Document(page_content=paragraphs_html)] docs_transformed = bs_transformer.transform_documents(documents, ...
@pytest.mark.requires('bs4') def test_extract_html() ->None: bs_transformer = BeautifulSoupTransformer() paragraphs_html = ( '<html>Begin of html tag<h1>Header</h1><p>First paragraph.</p>Middle of html tag<p>Second paragraph.</p>End of html tag</html>' ) documents = [Document(page_content=pa...
null
test_strip_whitespace
bs_transformer = BeautifulSoupTransformer() paragraphs_html = ( '<html><h1>Header</h1><p><span>First</span> paragraph.</p><p>Second paragraph. </p></html>' ) documents = [Document(page_content=paragraphs_html)] docs_transformed = bs_transformer.transform_documents(documents) assert docs_transformed[0].page_co...
@pytest.mark.requires('bs4') def test_strip_whitespace() ->None: bs_transformer = BeautifulSoupTransformer() paragraphs_html = ( '<html><h1>Header</h1><p><span>First</span> paragraph.</p><p>Second paragraph. </p></html>' ) documents = [Document(page_content=paragraphs_html)] docs_trans...
null
_identifying_params
return {}
@property def _identifying_params(self) ->Dict[str, Any]: return {}
null
_construct_json_body
return {'inputs': prompt, 'parameters': params}
def _construct_json_body(self, prompt: str, params: dict) ->dict: return {'inputs': prompt, 'parameters': params}
null
_Continue
self.fill('continue')
def _Continue(self, t): self.fill('continue')
null
deactivate_selection_scorer
""" Deactivates the selection scorer, meaning that the chain will no longer attempt to use the selection scorer to score responses. """ self.selection_scorer_activated = False
def deactivate_selection_scorer(self) ->None: """ Deactivates the selection scorer, meaning that the chain will no longer attempt to use the selection scorer to score responses. """ self.selection_scorer_activated = False
Deactivates the selection scorer, meaning that the chain will no longer attempt to use the selection scorer to score responses.
_encode
token_ids_with_start_and_end_token_ids = self.tokenizer.encode(text, max_length=self._max_length_equal_32_bit_integer, truncation= 'do_not_truncate') return token_ids_with_start_and_end_token_ids
def _encode(self, text: str) ->List[int]: token_ids_with_start_and_end_token_ids = self.tokenizer.encode(text, max_length=self._max_length_equal_32_bit_integer, truncation= 'do_not_truncate') return token_ids_with_start_and_end_token_ids
null
load
"""Load from a file path.""" with open(self.file_path, encoding='utf8') as f: tsv = list(csv.reader(f, delimiter='\t')) lines = [line for line in tsv if len(line) > 1] text = '' for i, line in enumerate(lines): if line[9] == 'SpaceAfter=No' or i == len(lines) - 1: text += line[1] else: t...
def load(self) ->List[Document]: """Load from a file path.""" with open(self.file_path, encoding='utf8') as f: tsv = list(csv.reader(f, delimiter='\t')) lines = [line for line in tsv if len(line) > 1] text = '' for i, line in enumerate(lines): if line[9] == 'SpaceAfter=No' or i =...
Load from a file path.
_get_parameters
""" Performs sanity check, preparing parameters in format needed by textgen. Args: stop (Optional[List[str]]): List of stop sequences for textgen. Returns: Dictionary containing the combined parameters. """ if self.stopping_strings and stop is not None: rais...
def _get_parameters(self, stop: Optional[List[str]]=None) ->Dict[str, Any]: """ Performs sanity check, preparing parameters in format needed by textgen. Args: stop (Optional[List[str]]): List of stop sequences for textgen. Returns: Dictionary containing the combined...
Performs sanity check, preparing parameters in format needed by textgen. Args: stop (Optional[List[str]]): List of stop sequences for textgen. Returns: Dictionary containing the combined parameters.
head_file
"""Get the first n lines of a file.""" try: with open(path, 'r') as f: return [str(line) for line in itertools.islice(f, n)] except Exception: return []
def head_file(path: str, n: int) ->List[str]: """Get the first n lines of a file.""" try: with open(path, 'r') as f: return [str(line) for line in itertools.islice(f, n)] except Exception: return []
Get the first n lines of a file.
test_chat_google_genai_invoke_multimodal_invalid_model
messages: list = [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=_MODEL) with pytest.raises(ChatGoogleGenerativeAIError): llm.invoke(messages)
def test_chat_google_genai_invoke_multimodal_invalid_model() ->None: messages: list = [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(mode...
null
clear
"""Clear session memory from this memory and cosmos.""" self.messages = [] if self._container: self._container.delete_item(item=self.session_id, partition_key=self. user_id)
def clear(self) ->None: """Clear session memory from this memory and cosmos.""" self.messages = [] if self._container: self._container.delete_item(item=self.session_id, partition_key= self.user_id)
Clear session memory from this memory and cosmos.
get_format_instructions
return FORMAT_INSTRUCTIONS
def get_format_instructions(self) ->str: return FORMAT_INSTRUCTIONS
null
_forward_propagate
try: import pandas as pd except ImportError as e: raise ImportError( 'Unable to import pandas, please install with `pip install pandas`.' ) from e entity_scope = {entity.name: entity for entity in self.causal_operations. entities} for entity in self.causal_operations.entities: if entity....
def _forward_propagate(self) ->None: try: import pandas as pd except ImportError as e: raise ImportError( 'Unable to import pandas, please install with `pip install pandas`.' ) from e entity_scope = {entity.name: entity for entity in self. causal_operations.en...
null
test_pairwise_embedding_distance_eval_chain_euclidean_distance
"""Test the euclidean distance.""" from scipy.spatial.distance import euclidean pairwise_embedding_distance_eval_chain.distance_metric = (EmbeddingDistance .EUCLIDEAN) result = pairwise_embedding_distance_eval_chain._compute_score(np.array( vectors)) expected = euclidean(*vectors) assert np.isclose(result, expe...
@pytest.mark.requires('scipy') def test_pairwise_embedding_distance_eval_chain_euclidean_distance( pairwise_embedding_distance_eval_chain: PairwiseEmbeddingDistanceEvalChain, vectors: Tuple[np.ndarray, np.ndarray] ) ->None: """Test the euclidean distance.""" from scipy.spatial.distance import euclid...
Test the euclidean distance.
from_params
"""Initialize DocArrayHnswSearch store. Args: embedding (Embeddings): Embedding function. work_dir (str): path to the location where all the data will be stored. n_dim (int): dimension of an embedding. dist_metric (str): Distance metric for DocArrayHnswSearch can...
@classmethod def from_params(cls, embedding: Embeddings, work_dir: str, n_dim: int, dist_metric: Literal['cosine', 'ip', 'l2']='cosine', max_elements: int= 1024, index: bool=True, ef_construction: int=200, ef: int=10, M: int=16, allow_replace_deleted: bool=True, num_threads: int=1, **kwargs: Any ) ->Doc...
Initialize DocArrayHnswSearch store. Args: embedding (Embeddings): Embedding function. work_dir (str): path to the location where all the data will be stored. n_dim (int): dimension of an embedding. dist_metric (str): Distance metric for DocArrayHnswSearch can be one of: "cosine", "ip", and "l2...
__init__
from azure.search.documents.indexes.models import SearchableField, SearchField, SearchFieldDataType, SimpleField """Initialize with necessary components.""" self.embedding_function = embedding_function default_fields = [SimpleField(name=FIELDS_ID, type=SearchFieldDataType. String, key=True, filterable=True), Search...
def __init__(self, azure_search_endpoint: str, azure_search_key: str, index_name: str, embedding_function: Callable, search_type: str= 'hybrid', semantic_configuration_name: Optional[str]=None, semantic_query_language: str='en-us', fields: Optional[List[SearchField ]]=None, vector_search: Optional[Vecto...
null
get_vectorstore
"""Get the vectorstore used for this example.""" return Chroma(collection_name=collection_name, persist_directory=str(Path( __file__).parent.parent / 'chroma_db_proposals'), embedding_function= OpenAIEmbeddings())
def get_vectorstore(collection_name: str='proposals'): """Get the vectorstore used for this example.""" return Chroma(collection_name=collection_name, persist_directory=str( Path(__file__).parent.parent / 'chroma_db_proposals'), embedding_function=OpenAIEmbeddings())
Get the vectorstore used for this example.
get_tools
"""Get the tools in the toolkit.""" return [MultionCreateSession(), MultionUpdateSession(), MultionCloseSession()]
def get_tools(self) ->List[BaseTool]: """Get the tools in the toolkit.""" return [MultionCreateSession(), MultionUpdateSession(), MultionCloseSession()]
Get the tools in the toolkit.
_approximate_search_query_with_boolean_filter
"""For Approximate k-NN Search, with Boolean Filter.""" return {'size': k, 'query': {'bool': {'filter': boolean_filter, subquery_clause: [{'knn': {vector_field: {'vector': query_vector, 'k': k}}}]}}}
def _approximate_search_query_with_boolean_filter(query_vector: List[float], boolean_filter: Dict, k: int=4, vector_field: str='vector_field', subquery_clause: str='must') ->Dict: """For Approximate k-NN Search, with Boolean Filter.""" return {'size': k, 'query': {'bool': {'filter': boolean_filter, ...
For Approximate k-NN Search, with Boolean Filter.
get_lc_namespace
"""Get the namespace of the langchain object.""" return ['langchain', 'schema', 'runnable']
@classmethod def get_lc_namespace(cls) ->List[str]: """Get the namespace of the langchain object.""" return ['langchain', 'schema', 'runnable']
Get the namespace of the langchain object.
is_lc_serializable
return False
@classmethod def is_lc_serializable(cls) ->bool: return False
null
_get_python_function_name
"""Get the name of a Python function.""" return function.__name__
def _get_python_function_name(function: Callable) ->str: """Get the name of a Python function.""" return function.__name__
Get the name of a Python function.
validate_environment
"""Validate that api key in environment.""" try: import fireworks.client except ImportError as e: raise ImportError( 'Could not import fireworks-ai python package. Please install it with `pip install fireworks-ai`.' ) from e fireworks_api_key = convert_to_secret_str(get_from_dict_or_env(values, ...
@root_validator() def validate_environment(cls, values: Dict) ->Dict: """Validate that api key in environment.""" try: import fireworks.client except ImportError as e: raise ImportError( 'Could not import fireworks-ai python package. Please install it with `pip install fireworks-...
Validate that api key in environment.
_create_retry_decorator
multiplier = 1 min_seconds = 1 max_seconds = 4 return retry(reraise=True, stop=stop_after_attempt(embeddings.max_retries), wait=wait_exponential(multiplier, min=min_seconds, max=max_seconds), retry=retry_if_exception_type(HTTPError), before_sleep=before_sleep_log (logger, logging.WARNING))
def _create_retry_decorator(embeddings: DashScopeEmbeddings) ->Callable[[ Any], Any]: multiplier = 1 min_seconds = 1 max_seconds = 4 return retry(reraise=True, stop=stop_after_attempt(embeddings. max_retries), wait=wait_exponential(multiplier, min=min_seconds, max=max_seconds), retry...
null
_prepare_batches
"""Splits texts in batches based on current maximum batch size and maximum tokens per request. """ text_index = 0 texts_len = len(texts) batch_token_len = 0 batches: List[List[str]] = [] current_batch: List[str] = [] if texts_len == 0: return [] while text_index < texts_len: current_text = texts...
@staticmethod def _prepare_batches(texts: List[str], batch_size: int) ->List[List[str]]: """Splits texts in batches based on current maximum batch size and maximum tokens per request. """ text_index = 0 texts_len = len(texts) batch_token_len = 0 batches: List[List[str]] = [] curr...
Splits texts in batches based on current maximum batch size and maximum tokens per request.
from_texts
vespa = cls(embedding_function=embedding, **kwargs) vespa.add_texts(texts=texts, metadatas=metadatas, ids=ids) return vespa
@classmethod def from_texts(cls: Type[VespaStore], texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]]=None, ids: Optional[List[ str]]=None, **kwargs: Any) ->VespaStore: vespa = cls(embedding_function=embedding, **kwargs) vespa.add_texts(texts=texts, metadatas=metadatas, ids=ids) ...
null
_to_chat_prompt
"""Convert a list of messages into a prompt format expected by wrapped LLM.""" if not messages: raise ValueError('at least one HumanMessage must be provided') if not isinstance(messages[-1], HumanMessage): raise ValueError('last message must be a HumanMessage') messages_dicts = [self._to_chatml_format(m) for m ...
def _to_chat_prompt(self, messages: List[BaseMessage]) ->str: """Convert a list of messages into a prompt format expected by wrapped LLM.""" if not messages: raise ValueError('at least one HumanMessage must be provided') if not isinstance(messages[-1], HumanMessage): raise ValueError('last m...
Convert a list of messages into a prompt format expected by wrapped LLM.
_create_thread_and_run
params = {k: v for k, v in input.items() if k in ('instructions', 'model', 'tools', 'run_metadata')} run = self.client.beta.threads.create_and_run(assistant_id=self. assistant_id, thread=thread, **params) return run
def _create_thread_and_run(self, input: dict, thread: dict) ->Any: params = {k: v for k, v in input.items() if k in ('instructions', 'model', 'tools', 'run_metadata')} run = self.client.beta.threads.create_and_run(assistant_id=self. assistant_id, thread=thread, **params) return run
null
test_load_no_content
"""Returns a Document without content.""" api_client = PubMedLoader(query='37548971') docs = api_client.load() print(docs) assert len(docs) > 0 assert docs[0].page_content == ''
def test_load_no_content() ->None: """Returns a Document without content.""" api_client = PubMedLoader(query='37548971') docs = api_client.load() print(docs) assert len(docs) > 0 assert docs[0].page_content == ''
Returns a Document without content.
list_branches_in_repo
""" Fetches a list of all branches in the repository. Returns: str: A plaintext report containing the names of the branches. """ try: branches = [branch.name for branch in self.github_repo_instance. get_branches()] if branches: branches_str = '\n'.join(branch...
def list_branches_in_repo(self) ->str: """ Fetches a list of all branches in the repository. Returns: str: A plaintext report containing the names of the branches. """ try: branches = [branch.name for branch in self.github_repo_instance. get_branches()] ...
Fetches a list of all branches in the repository. Returns: str: A plaintext report containing the names of the branches.
wrapper
other = kwargs.get('other') if 'other' in kwargs else None if not other: for arg in args: if isinstance(arg, type(instance)): other = arg break if isinstance(other, type(instance)): raise ValueError( 'Equality operators are overridden for FilterExpression creation. Use .e...
@wraps(func) def wrapper(instance: Any, *args: Any, **kwargs: Any) ->Any: other = kwargs.get('other') if 'other' in kwargs else None if not other: for arg in args: if isinstance(arg, type(instance)): other = arg break if isinstance(other, type(instance)): ...
null
_compute_score
"""Compute the score based on the distance metric. Args: vectors (np.ndarray): The input vectors. Returns: float: The computed score. """ metric = self._get_metric(self.distance_metric) score = metric(vectors[0].reshape(1, -1), vectors[1].reshape(1, -1)).item() return s...
def _compute_score(self, vectors: np.ndarray) ->float: """Compute the score based on the distance metric. Args: vectors (np.ndarray): The input vectors. Returns: float: The computed score. """ metric = self._get_metric(self.distance_metric) score = metric(ve...
Compute the score based on the distance metric. Args: vectors (np.ndarray): The input vectors. Returns: float: The computed score.
similarity_search
"""Find the most similar documents to the given query.""" raise NotImplementedError()
def similarity_search(self, query: str, k: int=4, **kwargs: Any) ->List[ Document]: """Find the most similar documents to the given query.""" raise NotImplementedError()
Find the most similar documents to the given query.
_select_relevance_score_fn
return self.relevance_score_fn if self.relevance_score_fn else _default_score_normalizer
def _select_relevance_score_fn(self) ->Callable[[float], float]: return (self.relevance_score_fn if self.relevance_score_fn else _default_score_normalizer)
null
validate_environment
"""Validate that api key exists in environment.""" openweathermap_api_key = get_from_dict_or_env(values, 'openweathermap_api_key', 'OPENWEATHERMAP_API_KEY') try: import pyowm except ImportError: raise ImportError( 'pyowm is not installed. Please install it with `pip install pyowm`') owm = pyowm.OWM(...
@root_validator(pre=True) def validate_environment(cls, values: Dict) ->Dict: """Validate that api key exists in environment.""" openweathermap_api_key = get_from_dict_or_env(values, 'openweathermap_api_key', 'OPENWEATHERMAP_API_KEY') try: import pyowm except ImportError: raise I...
Validate that api key exists in environment.
test_show_progress
"""Verify that file system loader works with a progress bar.""" loader = FileSystemBlobLoader(toy_dir) blobs = list(loader.yield_blobs()) assert len(blobs) == loader.count_matching_files()
@pytest.mark.requires('tqdm') def test_show_progress(toy_dir: str) ->None: """Verify that file system loader works with a progress bar.""" loader = FileSystemBlobLoader(toy_dir) blobs = list(loader.yield_blobs()) assert len(blobs) == loader.count_matching_files()
Verify that file system loader works with a progress bar.
map
""" Return a new Runnable that maps a list of inputs to a list of outputs, by calling invoke() with each input. """ return RunnableEach(bound=self)
def map(self) ->Runnable[List[Input], List[Output]]: """ Return a new Runnable that maps a list of inputs to a list of outputs, by calling invoke() with each input. """ return RunnableEach(bound=self)
Return a new Runnable that maps a list of inputs to a list of outputs, by calling invoke() with each input.
_upload_to_gcs
"""Uploads data to gcs_location. Args: data: The data that will be stored. gcs_location: The location where the data will be stored. """ bucket = self.gcs_client.get_bucket(self.gcs_bucket_name) blob = bucket.blob(gcs_location) blob.upload_from_string(data)
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 stored. """ bucket = self.gcs_client.get_bucket(self.gcs_bucket_name) blob = bu...
Uploads data to gcs_location. Args: data: The data that will be stored. gcs_location: The location where the data will be stored.
test_video_id_extraction
"""Test that the video id is extracted from a youtube url""" assert YoutubeLoader.extract_video_id(youtube_url) == expected_video_id
@pytest.mark.parametrize('youtube_url, expected_video_id', [( 'http://www.youtube.com/watch?v=-wtIMTCHWuI', '-wtIMTCHWuI'), ( 'http://youtube.com/watch?v=-wtIMTCHWuI', '-wtIMTCHWuI'), ( 'http://m.youtube.com/watch?v=-wtIMTCHWuI', '-wtIMTCHWuI'), ( 'http://youtu.be/-wtIMTCHWuI', '-wtIMTCHWuI'), ( 'ht...
Test that the video id is extracted from a youtube url
clear
"""Clear cache. This is for all LLMs at once.""" self.kv_cache.clear()
def clear(self, **kwargs: Any) ->None: """Clear cache. This is for all LLMs at once.""" self.kv_cache.clear()
Clear cache. This is for all LLMs at once.
_call
"""Call out to Titan Takeoff generate endpoint. Args: prompt: The prompt to pass into the model. stop: Optional list of stop words to use when generating. Returns: The string generated by the model. Example: .. code-block:: python ...
def _call(self, prompt: str, stop: Optional[List[str]]=None, run_manager: Optional[CallbackManagerForLLMRun]=None, **kwargs: Any) ->str: """Call out to Titan Takeoff generate endpoint. Args: prompt: The prompt to pass into the model. stop: Optional list of stop words to use when...
Call out to Titan Takeoff generate endpoint. Args: prompt: The prompt to pass into the model. stop: Optional list of stop words to use when generating. Returns: The string generated by the model. Example: .. code-block:: python prompt = "What is the capital of the United Kingdom?" re...
_generate
params = {**self._default_params, **kwargs} encoded_prompts = self.tokenizer(prompts)['input_ids'] tokenized_prompts = [self.tokenizer.convert_ids_to_tokens(encoded_prompt) for encoded_prompt in encoded_prompts] results = self.client.generate_batch(tokenized_prompts, **params) sequences = [result.sequences_ids[0] f...
def _generate(self, prompts: List[str], stop: Optional[List[str]]=None, run_manager: Optional[CallbackManagerForLLMRun]=None, **kwargs: Any ) ->LLMResult: params = {**self._default_params, **kwargs} encoded_prompts = self.tokenizer(prompts)['input_ids'] tokenized_prompts = [self.tokenizer.convert_id...
null
_persist_run
pass
def _persist_run(self, run: Run) ->None: pass
null
load_memory_variables
"""Load all vars from sub-memories.""" memory_data: Dict[str, Any] = {} for memory in self.memories: data = memory.load_memory_variables(inputs) for key, value in data.items(): if key in memory_data: raise ValueError( f'The variable {key} is repeated in the CombinedMemory.') ...
def load_memory_variables(self, inputs: Dict[str, Any]) ->Dict[str, str]: """Load all vars from sub-memories.""" memory_data: Dict[str, Any] = {} for memory in self.memories: data = memory.load_memory_variables(inputs) for key, value in data.items(): if key in memory_data: ...
Load all vars from sub-memories.
decode_to_str
return item.numpy().decode('utf-8')
def decode_to_str(item: tf.Tensor) ->str: return item.numpy().decode('utf-8')
null
_format_memory_detail
created_time = memory.metadata['created_at'].strftime('%B %d, %Y, %I:%M %p') return f'{prefix}[{created_time}] {memory.page_content.strip()}'
def _format_memory_detail(self, memory: Document, prefix: str='') ->str: created_time = memory.metadata['created_at'].strftime('%B %d, %Y, %I:%M %p' ) return f'{prefix}[{created_time}] {memory.page_content.strip()}'
null
from_texts
""" Create a new ElasticKnnSearch instance and add a list of texts to the Elasticsearch index. Args: texts (List[str]): The texts to add to the index. embedding (Embeddings): The embedding model to use for transforming the texts into vectors. ...
@classmethod def from_texts(cls, texts: List[str], embedding: Embeddings, metadatas: Optional[List[Dict[Any, Any]]]=None, **kwargs: Any) ->ElasticKnnSearch: """ Create a new ElasticKnnSearch instance and add a list of texts to the Elasticsearch index. Args: texts (List[s...
Create a new ElasticKnnSearch instance and add a list of texts to the Elasticsearch index. Args: texts (List[str]): The texts to add to the index. embedding (Embeddings): The embedding model to use for transforming the texts into vectors. metadatas (List[Dict[Any, Any]], optional): A list of me...
_import_gmail_GmailGetMessage
from langchain_community.tools.gmail import GmailGetMessage return GmailGetMessage
def _import_gmail_GmailGetMessage() ->Any: from langchain_community.tools.gmail import GmailGetMessage return GmailGetMessage
null
delete_collection
self.logger.debug('Trying to delete collection') drop_statement = text(f'DROP TABLE IF EXISTS {self.collection_name};') with self.engine.connect() as conn: with conn.begin(): conn.execute(drop_statement)
def delete_collection(self) ->None: self.logger.debug('Trying to delete collection') drop_statement = text(f'DROP TABLE IF EXISTS {self.collection_name};') with self.engine.connect() as conn: with conn.begin(): conn.execute(drop_statement)
null
format_auto_embed_off
""" Converts the `BasedOn` and `ToSelectFrom` into a format that can be used by VW """ chosen_action, cost, prob = self.get_label(event) context_emb, action_embs = self.get_context_and_action_embeddings(event) example_string = '' example_string += 'shared ' for context_item in context_emb: for ns, b...
def format_auto_embed_off(self, event: PickBestEvent) ->str: """ Converts the `BasedOn` and `ToSelectFrom` into a format that can be used by VW """ chosen_action, cost, prob = self.get_label(event) context_emb, action_embs = self.get_context_and_action_embeddings(event) example_string = ...
Converts the `BasedOn` and `ToSelectFrom` into a format that can be used by VW
test_final_answer_before_parsable_action
llm_output = """Final Answer: The best pizza to eat is margaritta Action: foo Action Input: bar """ agent_finish: AgentFinish = mrkl_output_parser.parse_folder(llm_output) assert agent_finish.return_values.get('output' ) == 'The best pizza to eat is margaritta'
def test_final_answer_before_parsable_action() ->None: llm_output = """Final Answer: The best pizza to eat is margaritta Action: foo Action Input: bar """ agent_finish: AgentFinish = mrkl_output_parser.parse_folder(llm_output) assert agent_finish.return_values.get('output' )...
null
messages
"""Retrieve the messages from PostgreSQL""" query = ( f'SELECT message FROM {self.table_name} WHERE session_id = %s ORDER BY id;' ) self.cursor.execute(query, (self.session_id,)) items = [record['message'] for record in self.cursor.fetchall()] messages = messages_from_dict(items) return messages
@property def messages(self) ->List[BaseMessage]: """Retrieve the messages from PostgreSQL""" query = ( f'SELECT message FROM {self.table_name} WHERE session_id = %s ORDER BY id;' ) self.cursor.execute(query, (self.session_id,)) items = [record['message'] for record in self.cursor.fetcha...
Retrieve the messages from PostgreSQL
_get_and_update_kg
"""Get and update knowledge graph from the conversation history.""" prompt_input_key = self._get_prompt_input_key(inputs) knowledge = self.get_knowledge_triplets(inputs[prompt_input_key]) for triple in knowledge: self.kg.add_triple(triple)
def _get_and_update_kg(self, inputs: Dict[str, Any]) ->None: """Get and update knowledge graph from the conversation history.""" prompt_input_key = self._get_prompt_input_key(inputs) knowledge = self.get_knowledge_triplets(inputs[prompt_input_key]) for triple in knowledge: self.kg.add_triple(tri...
Get and update knowledge graph from the conversation history.
_call
"""Run text through and get agent response.""" name_to_tool_map = {tool.name: tool for tool in self.tools} color_mapping = get_color_mapping([tool.name for tool in self.tools], excluded_colors=['green', 'red']) intermediate_steps: List[Tuple[AgentAction, str]] = [] iterations = 0 time_elapsed = 0.0 start_time = tim...
def _call(self, inputs: Dict[str, str], run_manager: Optional[ CallbackManagerForChainRun]=None) ->Dict[str, Any]: """Run text through and get agent response.""" name_to_tool_map = {tool.name: tool for tool in self.tools} color_mapping = get_color_mapping([tool.name for tool in self.tools], excl...
Run text through and get agent response.
test_astradb_vectorstore_similarity_scale
"""Scale of the similarity scores.""" store_parseremb.add_texts(texts=[json.dumps([1, 1]), json.dumps([-1, -1])], ids=['near', 'far']) res1 = store_parseremb.similarity_search_with_score(json.dumps([0.5, 0.5]), k=2 ) scores = [sco for _, sco in res1] sco_near, sco_far = scores assert abs(1 - sco_near) < 0.001 a...
def test_astradb_vectorstore_similarity_scale(self, store_parseremb: AstraDB ) ->None: """Scale of the similarity scores.""" store_parseremb.add_texts(texts=[json.dumps([1, 1]), json.dumps([-1, -1 ])], ids=['near', 'far']) res1 = store_parseremb.similarity_search_with_score(json.dumps([0.5, ...
Scale of the similarity scores.
_get_opensearch_client
"""Get OpenSearch client from the opensearch_url, otherwise raise error.""" try: opensearch = _import_opensearch() client = opensearch(opensearch_url, **kwargs) except ValueError as e: raise ImportError( f'OpenSearch client string provided is not in proper format. Got error: {e} ' ) return c...
def _get_opensearch_client(opensearch_url: str, **kwargs: Any) ->Any: """Get OpenSearch client from the opensearch_url, otherwise raise error.""" try: opensearch = _import_opensearch() client = opensearch(opensearch_url, **kwargs) except ValueError as e: raise ImportError( ...
Get OpenSearch client from the opensearch_url, otherwise raise error.
on_text
pass
def on_text(self, text: str, color: Optional[str]=None, end: str='', ** kwargs: Any) ->None: pass
null
_import_golden_query
from langchain_community.utilities.golden_query import GoldenQueryAPIWrapper return GoldenQueryAPIWrapper
def _import_golden_query() ->Any: from langchain_community.utilities.golden_query import GoldenQueryAPIWrapper return GoldenQueryAPIWrapper
null
test_runnable_branch_invoke
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 > 0 and x < 5, lambda x: x + 1), (lambda x: x > 5, lambda x: x * 10), lambda x: x - 1) assert branch.invoke(1) == 2 a...
def test_runnable_branch_invoke() ->None: 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 > 0 and x < 5, lambda x: x + 1), (lambda x: x > 5, ...
null
get_num_tokens
"""Get the number of tokens present in the text. Useful for checking if an input will fit in a model's context window. Args: text: The string input to tokenize. Returns: The integer number of tokens in the text. """ if self.is_gemini: raise ValueError('Coun...
def get_num_tokens(self, text: str) ->int: """Get the number of tokens present in the text. Useful for checking if an input will fit in a model's context window. Args: text: The string input to tokenize. Returns: The integer number of tokens in the text. ""...
Get the number of tokens present in the text. Useful for checking if an input will fit in a model's context window. Args: text: The string input to tokenize. Returns: The integer number of tokens in the text.
test_prompt_from_jinja2_template_multiple_inputs_with_repeats
"""Test with multiple input variables and repeats.""" template = """Hello world Your variable: {{ foo }} {# This will not get rendered #} {% if bar %} You just set bar boolean variable to true {% endif %} {% for i in foo_list %} {{ i }} {% endfor %} {% if bar %} Your variable again: {{ foo }} {% endif %} """ promp...
@pytest.mark.requires('jinja2') def test_prompt_from_jinja2_template_multiple_inputs_with_repeats() ->None: """Test with multiple input variables and repeats.""" template = """Hello world Your variable: {{ foo }} {# This will not get rendered #} {% if bar %} You just set bar boolean variable to true {% endif...
Test with multiple input variables and repeats.
test_vald_search_by_vector
"""Test end to end construction and search by vector.""" texts = ['foo', 'bar', 'baz'] metadatas = [{'page': i} for i in range(len(texts))] docsearch = _vald_from_texts(metadatas=metadatas) time.sleep(WAIT_TIME) embedding = FakeEmbeddings().embed_query('foo') output = docsearch.similarity_search_by_vector(embedding, k=...
def test_vald_search_by_vector() ->None: """Test end to end construction and search by vector.""" texts = ['foo', 'bar', 'baz'] metadatas = [{'page': i} for i in range(len(texts))] docsearch = _vald_from_texts(metadatas=metadatas) time.sleep(WAIT_TIME) embedding = FakeEmbeddings().embed_query('f...
Test end to end construction and search by vector.
test_api_key_masked_when_passed_via_constructor
"""Test initialization with an API key provided via the initializer""" llm = AI21(ai21_api_key='secret-api-key') print(llm.ai21_api_key, end='') captured = capsys.readouterr() assert captured.out == '**********'
def test_api_key_masked_when_passed_via_constructor(capsys: CaptureFixture ) ->None: """Test initialization with an API key provided via the initializer""" llm = AI21(ai21_api_key='secret-api-key') print(llm.ai21_api_key, end='') captured = capsys.readouterr() assert captured.out == '**********'
Test initialization with an API key provided via the initializer
_iter_next_step
"""Take a single step in the thought-action-observation loop. Override this to take control of how the agent makes and acts on choices. """ try: intermediate_steps = self._prepare_intermediate_steps(intermediate_steps) output = self.agent.plan(intermediate_steps, callbacks=run_manager. ...
def _iter_next_step(self, name_to_tool_map: Dict[str, BaseTool], color_mapping: Dict[str, str], inputs: Dict[str, str], intermediate_steps: List[Tuple[AgentAction, str]], run_manager: Optional[CallbackManagerForChainRun]=None) ->Iterator[Union[AgentFinish, AgentAction, AgentStep]]: """Take a single ...
Take a single step in the thought-action-observation loop. Override this to take control of how the agent makes and acts on choices.
test_l2
"""Test Flat L2 distance.""" docsearch = Redis.from_texts(texts, FakeEmbeddings(), redis_url= TEST_REDIS_URL, vector_schema=l2_schema) output = docsearch.similarity_search_with_score('far', k=2) _, score = output[1] assert score == EUCLIDEAN_SCORE assert drop(docsearch.index_name)
def test_l2(texts: List[str]) ->None: """Test Flat L2 distance.""" docsearch = Redis.from_texts(texts, FakeEmbeddings(), redis_url= TEST_REDIS_URL, vector_schema=l2_schema) output = docsearch.similarity_search_with_score('far', k=2) _, score = output[1] assert score == EUCLIDEAN_SCORE as...
Test Flat L2 distance.
test_openai_embedding_documents
"""Test openai embeddings.""" documents = ['foo bar'] embedding = OpenAIEmbeddings() output = embedding.embed_documents(documents) assert len(output) == 1 assert len(output[0]) == 1536
@pytest.mark.scheduled def test_openai_embedding_documents() ->None: """Test openai embeddings.""" documents = ['foo bar'] embedding = OpenAIEmbeddings() output = embedding.embed_documents(documents) assert len(output) == 1 assert len(output[0]) == 1536
Test openai embeddings.
_get_reddit_search
return RedditSearchRun(api_wrapper=RedditSearchAPIWrapper(**kwargs))
def _get_reddit_search(**kwargs: Any) ->BaseTool: return RedditSearchRun(api_wrapper=RedditSearchAPIWrapper(**kwargs))
null
create_metadata
"""Create metadata from fields. Args: fields: The fields of the document. The fields must be a dict. Returns: metadata: The metadata of the document. The metadata must be a dict. """ metadata: Dict[str, Any] = {} for key, value in fields.items(): if key == 'id' or key == 'document' or ...
def create_metadata(fields: Dict[str, Any]) ->Dict[str, Any]: """Create metadata from fields. Args: fields: The fields of the document. The fields must be a dict. Returns: metadata: The metadata of the document. The metadata must be a dict. """ metadata: Dict[str, Any] = {} for...
Create metadata from fields. Args: fields: The fields of the document. The fields must be a dict. Returns: metadata: The metadata of the document. The metadata must be a dict.