method_name
stringlengths
1
78
method_body
stringlengths
3
9.66k
full_code
stringlengths
31
10.7k
docstring
stringlengths
4
4.74k
_get_schema
from openapi_pydantic import Reference, Schema schema = parameter.param_schema if isinstance(schema, Reference): schema = spec.get_referenced_schema(schema) elif schema is None: return None elif not isinstance(schema, Schema): raise ValueError(f'Error dereferencing schema: {schema}') return schema
@staticmethod def _get_schema(parameter: Parameter, spec: OpenAPISpec) ->Optional[Schema]: from openapi_pydantic import Reference, Schema schema = parameter.param_schema if isinstance(schema, Reference): schema = spec.get_referenced_schema(schema) elif schema is None: return None eli...
null
test_search
""" Test that `foo` is closest to `foo` Here k is 1 """ output = self.vectorstore.similarity_search(query='foo', k=1, metadatas=[ 'author', 'category']) assert output[0].page_content == 'foo' assert output[0].metadata['author'] == 'Adam' assert output[0].metadata['category'] == 'Music' asser...
def test_search(self) ->None: """ Test that `foo` is closest to `foo` Here k is 1 """ output = self.vectorstore.similarity_search(query='foo', k=1, metadatas =['author', 'category']) assert output[0].page_content == 'foo' assert output[0].metadata['author'] == 'Adam' ...
Test that `foo` is closest to `foo` Here k is 1
test_pypdf_loader
"""Test PyPDFLoader.""" file_path = Path(__file__).parent.parent / 'examples/hello.pdf' loader = PyPDFLoader(str(file_path)) docs = loader.load() assert len(docs) == 1 file_path = Path(__file__).parent.parent / 'examples/layout-parser-paper.pdf' loader = PyPDFLoader(str(file_path)) docs = loader.load() assert len(docs)...
def test_pypdf_loader() ->None: """Test PyPDFLoader.""" file_path = Path(__file__).parent.parent / 'examples/hello.pdf' loader = PyPDFLoader(str(file_path)) docs = loader.load() assert len(docs) == 1 file_path = Path(__file__ ).parent.parent / 'examples/layout-parser-paper.pdf' loade...
Test PyPDFLoader.
output_keys
""" Get the output keys. Returns: List[str]: The output keys. """ return ['score']
@property def output_keys(self) ->List[str]: """ Get the output keys. Returns: List[str]: The output keys. """ return ['score']
Get the output keys. Returns: List[str]: The output keys.
__init__
self.message = message super().__init__(self.message)
def __init__(self, message: str= 'The prompt contains toxic content and cannot be processed'): self.message = message super().__init__(self.message)
null
test_myscale_with_metadatas
"""Test end to end construction and search.""" texts = ['foo', 'bar', 'baz'] metadatas = [{'page': str(i)} for i in range(len(texts))] config = MyScaleSettings() config.table = 'test_myscale_with_metadatas' docsearch = MyScale.from_texts(texts=texts, embedding=FakeEmbeddings(), config=config, metadatas=metadatas) o...
def test_myscale_with_metadatas() ->None: """Test end to end construction and search.""" texts = ['foo', 'bar', 'baz'] metadatas = [{'page': str(i)} for i in range(len(texts))] config = MyScaleSettings() config.table = 'test_myscale_with_metadatas' docsearch = MyScale.from_texts(texts=texts, emb...
Test end to end construction and search.
__read_file
docs = [] csv_reader = csv.DictReader(csvfile, **self.csv_args) for i, row in enumerate(csv_reader): try: source = row[self.source_column ] if self.source_column is not None else self.file_path except KeyError: raise ValueError( f"Source column '{self.source_column}' not ...
def __read_file(self, csvfile: TextIOWrapper) ->List[Document]: docs = [] csv_reader = csv.DictReader(csvfile, **self.csv_args) for i, row in enumerate(csv_reader): try: source = row[self.source_column ] if self.source_column is not None else self.file_path except...
null
embed_query
"""Embed query text.""" embedding = embed_with_retry(self, self.model_name, text) return embedding['embedding']
def embed_query(self, text: str) ->List[float]: """Embed query text.""" embedding = embed_with_retry(self, self.model_name, text) return embedding['embedding']
Embed query text.
lazy_parse
"""Iterates over the Blob pages and returns an Iterator with a Document for each page, like the other parsers If multi-page document, blob.path has to be set to the S3 URI and for single page docs the blob.data is taken """ url_parse_result = urlparse(str(blob.path)) if blob.path else No...
def lazy_parse(self, blob: Blob) ->Iterator[Document]: """Iterates over the Blob pages and returns an Iterator with a Document for each page, like the other parsers If multi-page document, blob.path has to be set to the S3 URI and for single page docs the blob.data is taken """ u...
Iterates over the Blob pages and returns an Iterator with a Document for each page, like the other parsers If multi-page document, blob.path has to be set to the S3 URI and for single page docs the blob.data is taken
on_llm_end
"""Log records to deepeval when an LLM ends.""" from deepeval.metrics.answer_relevancy import AnswerRelevancy from deepeval.metrics.bias_classifier import UnBiasedMetric from deepeval.metrics.metric import Metric from deepeval.metrics.toxic_classifier import NonToxicMetric for metric in self.metrics: for i, generat...
def on_llm_end(self, response: LLMResult, **kwargs: Any) ->None: """Log records to deepeval when an LLM ends.""" from deepeval.metrics.answer_relevancy import AnswerRelevancy from deepeval.metrics.bias_classifier import UnBiasedMetric from deepeval.metrics.metric import Metric from deepeval.metrics....
Log records to deepeval when an LLM ends.
is_lc_serializable
return True
@classmethod def is_lc_serializable(cls) ->bool: return True
null
from_texts
"""Create Myscale wrapper with existing texts Args: texts (Iterable[str]): List or tuple of strings to be added embedding (Embeddings): Function to extract text embedding config (MyScaleSettings, Optional): Myscale configuration text_ids (Optional[Iterable], opti...
@classmethod def from_texts(cls, texts: Iterable[str], embedding: Embeddings, metadatas: Optional[List[Dict[Any, Any]]]=None, config: Optional[MyScaleSettings]= None, text_ids: Optional[Iterable[str]]=None, batch_size: int=32, ** kwargs: Any) ->MyScale: """Create Myscale wrapper with existing texts ...
Create Myscale wrapper with existing texts Args: texts (Iterable[str]): List or tuple of strings to be added embedding (Embeddings): Function to extract text embedding config (MyScaleSettings, Optional): Myscale configuration text_ids (Optional[Iterable], optional): IDs for the texts. ...
_stream
prompt = self._convert_messages_to_prompt(messages) params: Dict[str, Any] = {'prompt': prompt, **self._default_params, **kwargs} if stop: params['stop_sequences'] = stop stream_resp = self.client.completions.create(**params, stream=True) for data in stream_resp: delta = data.completion yield ChatGeneration...
def _stream(self, messages: List[BaseMessage], stop: Optional[List[str]]= None, run_manager: Optional[CallbackManagerForLLMRun]=None, **kwargs: Any ) ->Iterator[ChatGenerationChunk]: prompt = self._convert_messages_to_prompt(messages) params: Dict[str, Any] = {'prompt': prompt, **self._default_params, *...
null
example_notebook_path
current_dir = pathlib.Path(__file__).parent return os.path.join(current_dir, 'sample_documents', notebook_name)
@staticmethod def example_notebook_path(notebook_name: str) ->str: current_dir = pathlib.Path(__file__).parent return os.path.join(current_dir, 'sample_documents', notebook_name)
null
parse
"""Parse the output of the language model.""" text = text.upper() if 'INVALID' in text: return ThoughtValidity.INVALID elif 'INTERMEDIATE' in text: return ThoughtValidity.VALID_INTERMEDIATE elif 'VALID' in text: return ThoughtValidity.VALID_FINAL else: return ThoughtValidity.INVALID
def parse(self, text: str) ->ThoughtValidity: """Parse the output of the language model.""" text = text.upper() if 'INVALID' in text: return ThoughtValidity.INVALID elif 'INTERMEDIATE' in text: return ThoughtValidity.VALID_INTERMEDIATE elif 'VALID' in text: return ThoughtVali...
Parse the output of the language model.
create_multi_vector_retriever
""" Create retriever that indexes summaries, but returns raw images or texts :param vectorstore: Vectorstore to store embedded image sumamries :param image_summaries: Image summaries :param images: Base64 encoded images :return: Retriever """ store = LocalFileStore(str(Path(__file__).parent / ...
def create_multi_vector_retriever(vectorstore, image_summaries, images): """ Create retriever that indexes summaries, but returns raw images or texts :param vectorstore: Vectorstore to store embedded image sumamries :param image_summaries: Image summaries :param images: Base64 encoded images :r...
Create retriever that indexes summaries, but returns raw images or texts :param vectorstore: Vectorstore to store embedded image sumamries :param image_summaries: Image summaries :param images: Base64 encoded images :return: Retriever
test_tracer_tool_run
"""Test tracer on a Tool run.""" 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': 'end', 'time': datetime.now( timezone.utc)}], extra={}, execution_order=1, child...
@freeze_time('2023-01-01') def test_tracer_tool_run() ->None: """Test tracer on a Tool run.""" 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': 'e...
Test tracer on a Tool run.
get_token_ids_anthropic
"""Get the token ids for a string of text.""" client = _get_anthropic_client() tokenizer = client.get_tokenizer() encoded_text = tokenizer.encode(text) return encoded_text.ids
def get_token_ids_anthropic(text: str) ->List[int]: """Get the token ids for a string of text.""" client = _get_anthropic_client() tokenizer = client.get_tokenizer() encoded_text = tokenizer.encode(text) return encoded_text.ids
Get the token ids for a string of text.
_llm_type
"""Return type of llm.""" return 'nebula'
@property def _llm_type(self) ->str: """Return type of llm.""" return 'nebula'
Return type of llm.
exists
return key in self.store
def exists(self, key: str) ->bool: return key in self.store
null
validate_environment
"""Validate that api key and python package exists in environment.""" embaas_api_key = convert_to_secret_str(get_from_dict_or_env(values, 'embaas_api_key', 'EMBAAS_API_KEY')) values['embaas_api_key'] = embaas_api_key return values
@root_validator() def validate_environment(cls, values: Dict) ->Dict: """Validate that api key and python package exists in environment.""" embaas_api_key = convert_to_secret_str(get_from_dict_or_env(values, 'embaas_api_key', 'EMBAAS_API_KEY')) values['embaas_api_key'] = embaas_api_key return va...
Validate that api key and python package exists in environment.
_call
"""Call to Pipeline Cloud endpoint.""" try: from pipeline import PipelineCloud except ImportError: raise ImportError( 'Could not import pipeline-ai python package. Please install it with `pip install pipeline-ai`.' ) client = PipelineCloud(token=self.pipeline_api_key.get_secret_value()) params =...
def _call(self, prompt: str, stop: Optional[List[str]]=None, run_manager: Optional[CallbackManagerForLLMRun]=None, **kwargs: Any) ->str: """Call to Pipeline Cloud endpoint.""" try: from pipeline import PipelineCloud except ImportError: raise ImportError( 'Could not import pip...
Call to Pipeline Cloud endpoint.
texts
documents = TextLoader(os.path.join(os.path.dirname(__file__), 'fixtures', 'sharks.txt')).load() yield [doc.page_content for doc in documents]
@pytest.fixture(scope='function') def texts() ->Generator[List[str], None, None]: documents = TextLoader(os.path.join(os.path.dirname(__file__), 'fixtures', 'sharks.txt')).load() yield [doc.page_content for doc in documents]
null
test_vertexai_single_call_fails_no_message
chat = ChatVertexAI() with pytest.raises(ValueError) as exc_info: _ = chat([]) assert str(exc_info.value ) == 'You should provide at least one message to start the chat!'
def test_vertexai_single_call_fails_no_message() ->None: chat = ChatVertexAI() with pytest.raises(ValueError) as exc_info: _ = chat([]) assert str(exc_info.value ) == 'You should provide at least one message to start the chat!'
null
_call
"""Call the xinference model and return the output. Args: prompt: The prompt to use for generation. stop: Optional list of stop words to use when generating. generate_config: Optional dictionary for the configuration used for generation. Returns: ...
def _call(self, prompt: str, stop: Optional[List[str]]=None, run_manager: Optional[CallbackManagerForLLMRun]=None, **kwargs: Any) ->str: """Call the xinference model and return the output. Args: prompt: The prompt to use for generation. stop: Optional list of stop words to use w...
Call the xinference model and return the output. Args: prompt: The prompt to use for generation. stop: Optional list of stop words to use when generating. generate_config: Optional dictionary for the configuration used for generation. Returns: The generated string by the model.
max_marginal_relevance_search
"""Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. ...
def max_marginal_relevance_search(self, query: str, k: int=4, fetch_k: int= 20, lambda_mult: float=0.5, metadata: Optional[Dict[str, Any]]=None, ** kwargs: Any) ->List[Document]: """Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to que...
Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. fetch_k: Number of Documents to fetch to pass ...
input_keys
"""Return the input keys. :meta private: """ return [self.input_key]
@property def input_keys(self) ->List[str]: """Return the input keys. :meta private: """ return [self.input_key]
Return the input keys. :meta private:
_import_semadb
from langchain_community.vectorstores.semadb import SemaDB return SemaDB
def _import_semadb() ->Any: from langchain_community.vectorstores.semadb import SemaDB return SemaDB
null
_Index
self.dispatch(t.value)
def _Index(self, t): self.dispatch(t.value)
null
input_keys
"""Input keys. :meta private: """ return [self.input_key]
@property def input_keys(self) ->List[str]: """Input keys. :meta private: """ return [self.input_key]
Input keys. :meta private:
_get_mock_psychic_loader
psychic_loader = PsychicLoader(api_key=self.MOCK_API_KEY, connector_id=self .MOCK_CONNECTOR_ID, account_id=self.MOCK_ACCOUNT_ID) psychic_loader.psychic = mock_psychic return psychic_loader
def _get_mock_psychic_loader(self, mock_psychic: MagicMock) ->PsychicLoader: psychic_loader = PsychicLoader(api_key=self.MOCK_API_KEY, connector_id= self.MOCK_CONNECTOR_ID, account_id=self.MOCK_ACCOUNT_ID) psychic_loader.psychic = mock_psychic return psychic_loader
null
to_string
"""Return prompt as string.""" return self.text
def to_string(self) ->str: """Return prompt as string.""" return self.text
Return prompt as string.
test_scann_with_metadatas
"""Test end to end construction and search.""" texts = ['foo', 'bar', 'baz'] metadatas = [{'page': i} for i in range(len(texts))] docsearch = ScaNN.from_texts(texts, FakeEmbeddings(), metadatas=metadatas) expected_docstore = InMemoryDocstore({docsearch.index_to_docstore_id[0]: Document(page_content='foo', metadata=...
def test_scann_with_metadatas() ->None: """Test end to end construction and search.""" texts = ['foo', 'bar', 'baz'] metadatas = [{'page': i} for i in range(len(texts))] docsearch = ScaNN.from_texts(texts, FakeEmbeddings(), metadatas=metadatas) expected_docstore = InMemoryDocstore({docsearch.index_t...
Test end to end construction and search.
__init__
"""Initialize with necessary components.""" self.embedding_function = embedding_function self.index_name = index_name http_auth = kwargs.get('http_auth') self.is_aoss = _is_aoss_enabled(http_auth=http_auth) self.client = _get_opensearch_client(opensearch_url, **kwargs) self.engine = kwargs.get('engine')
def __init__(self, opensearch_url: str, index_name: str, embedding_function: Embeddings, **kwargs: Any): """Initialize with necessary components.""" self.embedding_function = embedding_function self.index_name = index_name http_auth = kwargs.get('http_auth') self.is_aoss = _is_aoss_enabled(http_...
Initialize with necessary components.
_to_args_and_kwargs
if isinstance(tool_input, str): return (tool_input,), {} else: return (), tool_input
def _to_args_and_kwargs(self, tool_input: Union[str, Dict]) ->Tuple[Tuple, Dict ]: if isinstance(tool_input, str): return (tool_input,), {} else: return (), tool_input
null
_import_tencentvectordb
from langchain_community.vectorstores.tencentvectordb import TencentVectorDB return TencentVectorDB
def _import_tencentvectordb() ->Any: from langchain_community.vectorstores.tencentvectordb import TencentVectorDB return TencentVectorDB
null
raise_deprecation
if 'llm' in values: warnings.warn( 'Directly instantiating an LLMBashChain with an llm is deprecated. Please instantiate with llm_chain or using the from_llm class method.' ) if 'llm_chain' not in values and values['llm'] is not None: prompt = values.get('prompt', PROMPT) values[...
@root_validator(pre=True) def raise_deprecation(cls, values: Dict) ->Dict: if 'llm' in values: warnings.warn( 'Directly instantiating an LLMBashChain with an llm is deprecated. Please instantiate with llm_chain or using the from_llm class method.' ) if 'llm_chain' not in valu...
null
_get_board
board = next((b for b in self.client.list_boards() if b.name == self. board_name), None) if not board: raise ValueError(f'Board `{self.board_name}` not found.') return board
def _get_board(self) ->Board: board = next((b for b in self.client.list_boards() if b.name == self. board_name), None) if not board: raise ValueError(f'Board `{self.board_name}` not found.') return board
null
from_texts
"""Construct Weaviate wrapper from raw documents. This is a user-friendly interface that: 1. Embeds documents. 2. Creates a new index for the embeddings in the Weaviate instance. 3. Adds the documents to the newly created Weaviate index. This is intended to be a qui...
@classmethod def from_texts(cls, texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]]=None, *, client: Optional[weaviate.Client]=None, weaviate_url: Optional[str]=None, weaviate_api_key: Optional[str]=None, batch_size: Optional[int]=None, index_name: Optional[str]=None, text_key: str...
Construct Weaviate wrapper from raw documents. This is a user-friendly interface that: 1. Embeds documents. 2. Creates a new index for the embeddings in the Weaviate instance. 3. Adds the documents to the newly created Weaviate index. This is intended to be a quick way to get started. Args: texts: Te...
from_names_and_descriptions
"""Convenience constructor.""" documents = [] for name, descriptions in names_and_descriptions: for description in descriptions: documents.append(Document(page_content=description, metadata={ 'name': name})) vectorstore = vectorstore_cls.from_documents(documents, embeddings) return cls(vectorsto...
@classmethod def from_names_and_descriptions(cls, names_and_descriptions: Sequence[Tuple [str, Sequence[str]]], vectorstore_cls: Type[VectorStore], embeddings: Embeddings, **kwargs: Any) ->EmbeddingRouterChain: """Convenience constructor.""" documents = [] for name, descriptions in names_and_descrip...
Convenience constructor.
_block_back_door_paths
intervention_entities = [entity_setting.name for entity_setting in self. intervention.entity_settings] for entity in self.causal_operations.entities: if entity.name in intervention_entities: entity.depends_on = [] entity.code = 'pass'
def _block_back_door_paths(self) ->None: intervention_entities = [entity_setting.name for entity_setting in self .intervention.entity_settings] for entity in self.causal_operations.entities: if entity.name in intervention_entities: entity.depends_on = [] entity.code = 'pa...
null
format_tool_to_openai_tool
"""Format tool into the OpenAI function API.""" function = format_tool_to_openai_function(tool) return {'type': 'function', 'function': function}
def format_tool_to_openai_tool(tool: BaseTool) ->ToolDescription: """Format tool into the OpenAI function API.""" function = format_tool_to_openai_function(tool) return {'type': 'function', 'function': function}
Format tool into the OpenAI function API.
search_index
return self._vector_store
@property def search_index(self) ->TigrisVectorStore: return self._vector_store
null
get_all_tool_names
"""Get a list of all possible tool names.""" return list(_BASE_TOOLS) + list(_EXTRA_OPTIONAL_TOOLS) + list(_EXTRA_LLM_TOOLS ) + list(_LLM_TOOLS)
def get_all_tool_names() ->List[str]: """Get a list of all possible tool names.""" return list(_BASE_TOOLS) + list(_EXTRA_OPTIONAL_TOOLS) + list( _EXTRA_LLM_TOOLS) + list(_LLM_TOOLS)
Get a list of all possible tool names.
_call
"""Call out to HuggingFace Hub's inference 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 HuggingFace Hub's inference endpoint. Args: prompt: The prompt to pass into the model. stop: Optional list of stop words to use...
Call out to HuggingFace Hub's inference 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 response = hf("Tell me a joke.")
similarity_search_by_vector
"""Return docs most similar to the embedding. Args: embedding: Embedding to look up documents similar to. k: The amount of neighbors that will be retrieved. filter: Optional. A list of Namespaces for filtering the matching results. For example: ...
def similarity_search_by_vector(self, embedding: List[float], k: int=4, filter: Optional[List[Namespace]]=None, **kwargs: Any) ->List[Document]: """Return docs most similar to the embedding. Args: embedding: Embedding to look up documents similar to. k: The amount of neighbors t...
Return docs most similar to the embedding. Args: embedding: Embedding to look up documents similar to. k: The amount of neighbors that will be retrieved. filter: Optional. A list of Namespaces for filtering the matching results. For example: [Namespace("color", ["red"], []), Namespace("shap...
config_specs
return get_unique_config_specs(spec for step in self.runnables.values() for spec in step.config_specs)
@property def config_specs(self) ->List[ConfigurableFieldSpec]: return get_unique_config_specs(spec for step in self.runnables.values() for spec in step.config_specs)
null
test_qdrant_from_texts_recreates_collection_on_force_recreate
"""Test if Qdrant.from_texts recreates the collection even if config mismatches""" from qdrant_client import QdrantClient collection_name = uuid.uuid4().hex with tempfile.TemporaryDirectory() as tmpdir: vec_store = Qdrant.from_texts(['lorem', 'ipsum', 'dolor', 'sit', 'amet' ], ConsistentFakeEmbeddings(dimen...
@pytest.mark.parametrize('vector_name', [None, 'custom-vector']) def test_qdrant_from_texts_recreates_collection_on_force_recreate(vector_name: Optional[str]) ->None: """Test if Qdrant.from_texts recreates the collection even if config mismatches""" from qdrant_client import QdrantClient collection_name...
Test if Qdrant.from_texts recreates the collection even if config mismatches
get_methods_for_path
"""Return a list of valid methods for the specified path.""" from openapi_pydantic import Operation path_item = self._get_path_strict(path) results = [] for method in HTTPVerb: operation = getattr(path_item, method.value, None) if isinstance(operation, Operation): results.append(method.value) return res...
def get_methods_for_path(self, path: str) ->List[str]: """Return a list of valid methods for the specified path.""" from openapi_pydantic import Operation path_item = self._get_path_strict(path) results = [] for method in HTTPVerb: operation = getattr(path_item, method.value, None) i...
Return a list of valid methods for the specified path.
_invocation_params
"""Combines the invocation parameters with default parameters.""" params = self._default_params if self.stop is not None and stop is not None: raise ValueError('`stop` found in both the input and default params.') elif self.stop is not None: params['stop'] = self.stop elif stop is not None: params['stop'] =...
def _invocation_params(self, stop: Optional[List[str]], **kwargs: Any) ->dict: """Combines the invocation parameters with default parameters.""" params = self._default_params if self.stop is not None and stop is not None: raise ValueError('`stop` found in both the input and default params.') eli...
Combines the invocation parameters with default parameters.
_create_collection
from pymilvus import Collection, CollectionSchema, DataType, FieldSchema, MilvusException from pymilvus.orm.types import infer_dtype_bydata dim = len(embeddings[0]) fields = [] if self._metadata_field is not None: fields.append(FieldSchema(self._metadata_field, DataType.JSON)) elif metadatas: for key, value in ...
def _create_collection(self, embeddings: list, metadatas: Optional[list[ dict]]=None) ->None: from pymilvus import Collection, CollectionSchema, DataType, FieldSchema, MilvusException from pymilvus.orm.types import infer_dtype_bydata dim = len(embeddings[0]) fields = [] if self._metadata_field i...
null
test_context_w_namespace_w_emb2
str1 = 'test' encoded_str1 = base.stringify_embedding(list(encoded_keyword + str1)) expected = [{'test_namespace': encoded_str1}] assert base.embed(base.Embed({'test_namespace': str1}), MockEncoder() ) == expected expected_embed_and_keep = [{'test_namespace': str1 + ' ' + encoded_str1}] assert base.embed(base.Embed...
@pytest.mark.requires('vowpal_wabbit_next') def test_context_w_namespace_w_emb2() ->None: str1 = 'test' encoded_str1 = base.stringify_embedding(list(encoded_keyword + str1)) expected = [{'test_namespace': encoded_str1}] assert base.embed(base.Embed({'test_namespace': str1}), MockEncoder() ) == e...
null
test_hologres_with_filter_no_match
"""Test end to end construction and search.""" texts = ['foo', 'bar', 'baz'] metadatas = [{'page': str(i)} for i in range(len(texts))] docsearch = Hologres.from_texts(texts=texts, table_name='test_table_filter', embedding=FakeEmbeddingsWithAdaDimension(), metadatas=metadatas, connection_string=CONNECTION_STRING...
def test_hologres_with_filter_no_match() ->None: """Test end to end construction and search.""" texts = ['foo', 'bar', 'baz'] metadatas = [{'page': str(i)} for i in range(len(texts))] docsearch = Hologres.from_texts(texts=texts, table_name= 'test_table_filter', embedding=FakeEmbeddingsWithAdaDim...
Test end to end construction and search.
exists
"""Check if the given keys exist in the SQLite database.""" with self._make_session() as session: records = session.query(UpsertionRecord.key).filter(and_( UpsertionRecord.key.in_(keys), UpsertionRecord.namespace == self. namespace)).all() found_keys = set(r.key for r in records) return [(k in found...
def exists(self, keys: Sequence[str]) ->List[bool]: """Check if the given keys exist in the SQLite database.""" with self._make_session() as session: records = session.query(UpsertionRecord.key).filter(and_( UpsertionRecord.key.in_(keys), UpsertionRecord.namespace == self.namespa...
Check if the given keys exist in the SQLite database.
test_chat_google_palm_system_message
"""Test Google PaLM Chat API wrapper with system message.""" chat = ChatGooglePalm() system_message = SystemMessage(content='You are to chat with the user.') human_message = HumanMessage(content='Hello') response = chat([system_message, human_message]) assert isinstance(response, BaseMessage) assert isinstance(response...
def test_chat_google_palm_system_message() ->None: """Test Google PaLM Chat API wrapper with system message.""" chat = ChatGooglePalm() system_message = SystemMessage(content='You are to chat with the user.') human_message = HumanMessage(content='Hello') response = chat([system_message, human_messag...
Test Google PaLM Chat API wrapper with system message.
_build_payloads
payloads = [] for i, text in enumerate(texts): if text is None: raise ValueError( 'At least one of the texts is None. Please remove it before calling .from_texts or .add_texts on Qdrant instance.' ) metadata = metadatas[i] if metadatas is not None else None payloads.append({c...
@classmethod def _build_payloads(cls, texts: Iterable[str], metadatas: Optional[List[ dict]], content_payload_key: str, metadata_payload_key: str) ->List[dict]: payloads = [] for i, text in enumerate(texts): if text is None: raise ValueError( 'At least one of the texts is...
null
delete
"""Delete documents from the index. Args: ids: List of ids of documents to delete """ try: from elasticsearch.helpers import BulkIndexError, bulk except ImportError: raise ImportError( 'Could not import elasticsearch python package. Please install it with `pip install elasti...
def delete(self, ids: Optional[List[str]]=None, **kwargs: Any) ->Optional[bool ]: """Delete documents from the index. Args: ids: List of ids of documents to delete """ try: from elasticsearch.helpers import BulkIndexError, bulk except ImportError: raise Impor...
Delete documents from the index. Args: ids: List of ids of documents to delete
__init__
"""Initialize the tensorflow_hub and tensorflow_text.""" super().__init__(**kwargs) try: import tensorflow_hub except ImportError: raise ImportError( 'Could not import tensorflow-hub python package. Please install it with `pip install tensorflow-hub``.' ) try: import tensorflow_text except I...
def __init__(self, **kwargs: Any): """Initialize the tensorflow_hub and tensorflow_text.""" super().__init__(**kwargs) try: import tensorflow_hub except ImportError: raise ImportError( 'Could not import tensorflow-hub python package. Please install it with `pip install tensor...
Initialize the tensorflow_hub and tensorflow_text.
enforce_stop_tokens
"""Cut off the text as soon as any stop words occur.""" return re.split('|'.join(stop), text, maxsplit=1)[0]
def enforce_stop_tokens(text: str, stop: List[str]) ->str: """Cut off the text as soon as any stop words occur.""" return re.split('|'.join(stop), text, maxsplit=1)[0]
Cut off the text as soon as any stop words occur.
batch_parse
"""Parses a list of blobs lazily. Args: blobs: a list of blobs to parse. gcs_output_path: a path on Google Cloud Storage to store parsing results. timeout_sec: a timeout to wait for Document AI to complete, in seconds. check_in_interval_sec: an interval to wait u...
def batch_parse(self, blobs: Sequence[Blob], gcs_output_path: Optional[str] =None, timeout_sec: int=3600, check_in_interval_sec: int=60) ->Iterator[ Document]: """Parses a list of blobs lazily. Args: blobs: a list of blobs to parse. gcs_output_path: a path on Google Cloud St...
Parses a list of blobs lazily. Args: blobs: a list of blobs to parse. gcs_output_path: a path on Google Cloud Storage to store parsing results. timeout_sec: a timeout to wait for Document AI to complete, in seconds. check_in_interval_sec: an interval to wait until next check whether parsing ope...
is_lc_serializable
return False
@classmethod def is_lc_serializable(cls) ->bool: return False
null
__repr__
"""Text representation for StarRocks Vector Store, prints backends, username and schemas. Easy to use with `str(StarRocks())` Returns: repr: string to show connection info and data schema """ _repr = f'\x1b[92m\x1b[1m{self.config.database}.{self.config.table} @ ' _repr += f'{sel...
def __repr__(self) ->str: """Text representation for StarRocks Vector Store, prints backends, username and schemas. Easy to use with `str(StarRocks())` Returns: repr: string to show connection info and data schema """ _repr = f'\x1b[92m\x1b[1m{self.config.database}.{self...
Text representation for StarRocks Vector Store, prints backends, username and schemas. Easy to use with `str(StarRocks())` Returns: repr: string to show connection info and data schema
marshal_spec
"""Convert the yaml or json serialized spec to a dict. Args: txt: The yaml or json serialized spec. Returns: dict: The spec as a dict. """ try: return json.loads(txt) except json.JSONDecodeError: return yaml.safe_load(txt)
def marshal_spec(txt: str) ->dict: """Convert the yaml or json serialized spec to a dict. Args: txt: The yaml or json serialized spec. Returns: dict: The spec as a dict. """ try: return json.loads(txt) except json.JSONDecodeError: return yaml.safe_load(txt)
Convert the yaml or json serialized spec to a dict. Args: txt: The yaml or json serialized spec. Returns: dict: The spec as a dict.
test_fastembed_embedding_query
"""Test fastembed embeddings for query.""" document = 'foo bar' embedding = FastEmbedEmbeddings(model_name=model_name, max_length=max_length) output = embedding.embed_query(document) assert len(output) == 384
@pytest.mark.parametrize('model_name', [ 'sentence-transformers/all-MiniLM-L6-v2', 'BAAI/bge-small-en-v1.5']) @pytest.mark.parametrize('max_length', [50, 512]) def test_fastembed_embedding_query(model_name: str, max_length: int) ->None: """Test fastembed embeddings for query.""" document = 'foo bar' emb...
Test fastembed embeddings for query.
test_passthrough_assign_schema
retriever = FakeRetriever() prompt = PromptTemplate.from_template('{context} {question}') fake_llm = FakeListLLM(responses=['a']) seq_w_assign: Runnable = RunnablePassthrough.assign(context=itemgetter( 'question') | retriever) | prompt | fake_llm assert seq_w_assign.input_schema.schema() == {'properties': {'questio...
def test_passthrough_assign_schema() ->None: retriever = FakeRetriever() prompt = PromptTemplate.from_template('{context} {question}') fake_llm = FakeListLLM(responses=['a']) seq_w_assign: Runnable = RunnablePassthrough.assign(context=itemgetter( 'question') | retriever) | prompt | fake_llm ...
null
pii_callback
return self.on_after_pii.__func__ is not BaseModerationCallbackHandler.on_after_pii
@property def pii_callback(self) ->bool: return (self.on_after_pii.__func__ is not BaseModerationCallbackHandler .on_after_pii)
null
test_api_key_is_readable
"""Test that the real secret value of the API key can be read""" azure_chat = request.getfixturevalue(fixture_name) assert azure_chat.endpoint_api_key.get_secret_value() == 'my-api-key'
def test_api_key_is_readable(self, fixture_name: str, request: FixtureRequest ) ->None: """Test that the real secret value of the API key can be read""" azure_chat = request.getfixturevalue(fixture_name) assert azure_chat.endpoint_api_key.get_secret_value() == 'my-api-key'
Test that the real secret value of the API key can be read
input_keys
"""Get input keys. Input refers to user input here.""" return ['input']
@property def input_keys(self) ->List[str]: """Get input keys. Input refers to user input here.""" return ['input']
Get input keys. Input refers to user input here.
__For_helper
self.fill(fill) self.dispatch(t.target) self.write(' in ') self.dispatch(t.iter) self.enter() self.dispatch(t.body) self.leave() if t.orelse: self.fill('else') self.enter() self.dispatch(t.orelse) self.leave()
def __For_helper(self, fill, t): self.fill(fill) self.dispatch(t.target) self.write(' in ') self.dispatch(t.iter) self.enter() self.dispatch(t.body) self.leave() if t.orelse: self.fill('else') self.enter() self.dispatch(t.orelse) self.leave()
null
visit_operation
args = [arg.accept(self) for arg in operation.arguments] return {'bool': {self._format_func(operation.operator): args}}
def visit_operation(self, operation: Operation) ->Dict: args = [arg.accept(self) for arg in operation.arguments] return {'bool': {self._format_func(operation.operator): args}}
null
default_call_api
method = _name_to_call_map[name]['method'] url = _name_to_call_map[name]['url'] path_params = fn_args.pop('path_params', {}) url = _format_url(url, path_params) if 'data' in fn_args and isinstance(fn_args['data'], dict): fn_args['data'] = json.dumps(fn_args['data']) _kwargs = {**fn_args, **kwargs} if headers is not...
def default_call_api(name: str, fn_args: dict, headers: Optional[dict]=None, params: Optional[dict]=None, **kwargs: Any) ->Any: method = _name_to_call_map[name]['method'] url = _name_to_call_map[name]['url'] path_params = fn_args.pop('path_params', {}) url = _format_url(url, path_params) if 'dat...
null
get_lc_namespace
"""Get the namespace of the langchain object.""" return ['langchain', 'chat_models', 'anthropic']
@classmethod def get_lc_namespace(cls) ->List[str]: """Get the namespace of the langchain object.""" return ['langchain', 'chat_models', 'anthropic']
Get the namespace of the langchain object.
from_llm_and_tools
"""Construct an agent from an LLM and tools.""" cls._validate_tools(tools) prompt = cls.create_prompt(tools, ai_prefix=ai_prefix, human_prefix= human_prefix, prefix=prefix, suffix=suffix, format_instructions= format_instructions, input_variables=input_variables) llm_chain = LLMChain(llm=llm, prompt=prompt, call...
@classmethod def from_llm_and_tools(cls, llm: BaseLanguageModel, tools: Sequence[ BaseTool], callback_manager: Optional[BaseCallbackManager]=None, output_parser: Optional[AgentOutputParser]=None, prefix: str=PREFIX, suffix: str=SUFFIX, format_instructions: str=FORMAT_INSTRUCTIONS, ai_prefix: str='AI', h...
Construct an agent from an LLM and tools.
similarity_search_with_score
"""Return typesense documents most similar to query, along with scores. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 10. Minimum 10 results would be returned. filter: typesense filter_by expression to filter...
def similarity_search_with_score(self, query: str, k: int=10, filter: Optional[str]='') ->List[Tuple[Document, float]]: """Return typesense documents most similar to query, along with scores. Args: query: Text to look up documents similar to. k: Number of Documents to return. De...
Return typesense documents most similar to query, along with scores. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 10. Minimum 10 results would be returned. filter: typesense filter_by expression to filter documents on Returns: List of Documen...
_call
"""Call out to Bedrock service model. 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 respons...
def _call(self, prompt: str, stop: Optional[List[str]]=None, run_manager: Optional[CallbackManagerForLLMRun]=None, **kwargs: Any) ->str: """Call out to Bedrock service model. Args: prompt: The prompt to pass into the model. stop: Optional list of stop words to use when generatin...
Call out to Bedrock service model. 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 response = llm("Tell me a joke.")
_load_refine_documents_chain
if 'initial_llm_chain' in config: initial_llm_chain_config = config.pop('initial_llm_chain') initial_llm_chain = load_chain_from_config(initial_llm_chain_config) elif 'initial_llm_chain_path' in config: initial_llm_chain = load_chain(config.pop('initial_llm_chain_path')) else: raise ValueError( ...
def _load_refine_documents_chain(config: dict, **kwargs: Any ) ->RefineDocumentsChain: if 'initial_llm_chain' in config: initial_llm_chain_config = config.pop('initial_llm_chain') initial_llm_chain = load_chain_from_config(initial_llm_chain_config) elif 'initial_llm_chain_path' in config: ...
null
test_pairwise_string_comparison_chain
llm = FakeLLM(queries={'a': """The values are the same. [[C]]""", 'b': """A is clearly better than b. [[A]]""", 'c': """B is clearly better than a. [[B]]"""}, sequential_responses=True) chain = PairwiseStringEvalChain.from_llm(llm=llm) res = chain.evaluate_string_pairs(prediction='I like pie.', prediction_b= ...
def test_pairwise_string_comparison_chain() ->None: llm = FakeLLM(queries={'a': 'The values are the same.\n[[C]]', 'b': """A is clearly better than b. [[A]]""", 'c': """B is clearly better than a. [[B]]"""}, sequential_responses=True) chain = PairwiseStringEvalChain.from_llm(llm=llm) res = c...
null
model
return Vicuna(llm=FakeLLM())
@pytest.fixture def model() ->Vicuna: return Vicuna(llm=FakeLLM())
null
on_retry
"""Run on a retry event."""
def on_retry(self, retry_state: RetryCallState, *, run_id: UUID, parent_run_id: Optional[UUID]=None, **kwargs: Any) ->Any: """Run on a retry event."""
Run on a retry event.
test_import_class
"""Test that the class can be imported.""" module_name = 'langchain_community.chat_models.huggingface' class_name = 'ChatHuggingFace' module = import_module(module_name) assert hasattr(module, class_name)
def test_import_class() ->None: """Test that the class can be imported.""" module_name = 'langchain_community.chat_models.huggingface' class_name = 'ChatHuggingFace' module = import_module(module_name) assert hasattr(module, class_name)
Test that the class can be imported.
_api_url
return self.api_url or self._default_api_url
@property def _api_url(self) ->str: return self.api_url or self._default_api_url
null
fake_vectorstore
vectorstore = InMemoryVectorstoreWithSearch() vectorstore.add_documents([Document(page_content='test', metadata={'foo': 'bar'})], ids=['test']) return vectorstore
@pytest.fixture() def fake_vectorstore() ->InMemoryVectorstoreWithSearch: vectorstore = InMemoryVectorstoreWithSearch() vectorstore.add_documents([Document(page_content='test', metadata={ 'foo': 'bar'})], ids=['test']) return vectorstore
null
test_promptlayer_openai_stop_valid
"""Test promptlayer openai stop logic on valid configuration.""" query = 'write an ordered list of five items' first_llm = PromptLayerOpenAI(stop='3', temperature=0) first_output = first_llm(query) second_llm = PromptLayerOpenAI(temperature=0) second_output = second_llm(query, stop=['3']) assert first_output == second_...
def test_promptlayer_openai_stop_valid() ->None: """Test promptlayer openai stop logic on valid configuration.""" query = 'write an ordered list of five items' first_llm = PromptLayerOpenAI(stop='3', temperature=0) first_output = first_llm(query) second_llm = PromptLayerOpenAI(temperature=0) sec...
Test promptlayer openai stop logic on valid configuration.
invoke
return self._call_with_config(self._invoke, input, config, **kwargs)
def invoke(self, input: Dict[str, Any], config: Optional[RunnableConfig]= None, **kwargs: Any) ->Dict[str, Any]: return self._call_with_config(self._invoke, input, config, **kwargs)
null
run
if mode == 'get_games_details': return self.details_of_games(game) elif mode == 'get_recommended_games': return self.recommended_games(game) else: raise ValueError(f'Invalid mode {mode} for Steam API.')
def run(self, mode: str, game: str) ->str: if mode == 'get_games_details': return self.details_of_games(game) elif mode == 'get_recommended_games': return self.recommended_games(game) else: raise ValueError(f'Invalid mode {mode} for Steam API.')
null
_process_response
if version == '1.0': text = response else: text = response['response'] if stop: text = enforce_stop_tokens(text, stop) return ''.join(text)
@staticmethod def _process_response(response: Any, stop: Optional[List[str]], version: Optional[str]) ->str: if version == '1.0': text = response else: text = response['response'] if stop: text = enforce_stop_tokens(text, stop) return ''.join(text)
null
update
"""Store llm generations in cache. Args: prompt (str): The prompt run through the language model. llm_string (str): The language model string. return_val (RETURN_VAL_TYPE): A list of language model generations. Raises: SdkException: Momento service or ne...
def update(self, prompt: str, llm_string: str, return_val: RETURN_VAL_TYPE ) ->None: """Store llm generations in cache. Args: prompt (str): The prompt run through the language model. llm_string (str): The language model string. return_val (RETURN_VAL_TYPE): A list of...
Store llm generations in cache. Args: prompt (str): The prompt run through the language model. llm_string (str): The language model string. return_val (RETURN_VAL_TYPE): A list of language model generations. Raises: SdkException: Momento service or network error Exception: Unexpected response
__init__
import psycopg from psycopg.rows import dict_row try: self.connection = psycopg.connect(connection_string) self.cursor = self.connection.cursor(row_factory=dict_row) except psycopg.OperationalError as error: logger.error(error) self.session_id = session_id self.table_name = table_name self._create_table_if_...
def __init__(self, session_id: str, connection_string: str= DEFAULT_CONNECTION_STRING, table_name: str='message_store'): import psycopg from psycopg.rows import dict_row try: self.connection = psycopg.connect(connection_string) self.cursor = self.connection.cursor(row_factory=dict_row) ...
null
get_gmail_credentials
"""Get credentials.""" Request, Credentials = import_google() InstalledAppFlow = import_installed_app_flow() creds = None scopes = scopes or DEFAULT_SCOPES token_file = token_file or DEFAULT_CREDS_TOKEN_FILE client_secrets_file = client_secrets_file or DEFAULT_CLIENT_SECRETS_FILE if os.path.exists(token_file): cred...
def get_gmail_credentials(token_file: Optional[str]=None, client_secrets_file: Optional[str]=None, scopes: Optional[List[str]]=None ) ->Credentials: """Get credentials.""" Request, Credentials = import_google() InstalledAppFlow = import_installed_app_flow() creds = None scopes = scopes or DE...
Get credentials.
similarity_search
"""Return Dingo documents most similar to query, along with scores. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. search_params: Dictionary of argument(s) to filter on metadata Returns: List of Docume...
def similarity_search(self, query: str, k: int=4, search_params: Optional[ dict]=None, timeout: Optional[int]=None, **kwargs: Any) ->List[Document]: """Return Dingo documents most similar to query, along with scores. Args: query: Text to look up documents similar to. k: Number o...
Return Dingo documents most similar to query, along with scores. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. search_params: Dictionary of argument(s) to filter on metadata Returns: List of Documents most similar to the query and score for each
_get_filtered_args
"""Get the arguments from a function's signature.""" schema = inferred_model.schema()['properties'] valid_keys = signature(func).parameters return {k: schema[k] for k in valid_keys if k not in ('run_manager', 'callbacks')}
def _get_filtered_args(inferred_model: Type[BaseModel], func: Callable) ->dict: """Get the arguments from a function's signature.""" schema = inferred_model.schema()['properties'] valid_keys = signature(func).parameters return {k: schema[k] for k in valid_keys if k not in ('run_manager', 'callba...
Get the arguments from a function's signature.
_completion_with_retry
return self.client.create(**kwargs)
@retry_decorator def _completion_with_retry(**kwargs: Any) ->Any: return self.client.create(**kwargs)
null
on_tool_start
"""Do nothing when tool starts."""
def on_tool_start(self, serialized: Dict[str, Any], input_str: str, ** kwargs: Any) ->None: """Do nothing when tool starts."""
Do nothing when tool starts.
on_tool_end
"""Run when tool ends running.""" aim = import_aim() self.step += 1 self.tool_ends += 1 self.ends += 1 resp = {'action': 'on_tool_end'} resp.update(self.get_custom_callback_meta()) self._run.track(aim.Text(output), name='on_tool_end', context=resp)
def on_tool_end(self, output: str, **kwargs: Any) ->None: """Run when tool ends running.""" aim = import_aim() self.step += 1 self.tool_ends += 1 self.ends += 1 resp = {'action': 'on_tool_end'} resp.update(self.get_custom_callback_meta()) self._run.track(aim.Text(output), name='on_tool_e...
Run when tool ends running.
_import_myscale_settings
from langchain_community.vectorstores.myscale import MyScaleSettings return MyScaleSettings
def _import_myscale_settings() ->Any: from langchain_community.vectorstores.myscale import MyScaleSettings return MyScaleSettings
null
test_api_key_masked_when_passed_from_env
"""Test initialization with an API key provided via an env variable""" monkeypatch.setenv('ANYSCALE_API_KEY', 'secret-api-key') llm = Anyscale(anyscale_api_base='test', model_name='test') print(llm.anyscale_api_key, end='') captured = capsys.readouterr() assert captured.out == '**********'
@pytest.mark.requires('openai') def test_api_key_masked_when_passed_from_env(monkeypatch: MonkeyPatch, capsys: CaptureFixture) ->None: """Test initialization with an API key provided via an env variable""" monkeypatch.setenv('ANYSCALE_API_KEY', 'secret-api-key') llm = Anyscale(anyscale_api_base='test', ...
Test initialization with an API key provided via an env variable
set
"""Set entity value in store.""" pass
@abstractmethod def set(self, key: str, value: Optional[str]) ->None: """Set entity value in store.""" pass
Set entity value in store.
__init__
if key is not None: kwargs[key] = value super().__init__(keys={k: (_coerce_set_value(v) if v is not None else None) for k, v in kwargs.items()}, prefix=prefix)
def __init__(self, key: Optional[str]=None, value: Optional[SetValue]=None, prefix: str='', **kwargs: SetValue): if key is not None: kwargs[key] = value super().__init__(keys={k: (_coerce_set_value(v) if v is not None else None) for k, v in kwargs.items()}, prefix=prefix)
null
test_api_key_masked_when_passed_via_constructor
chat = ChatGoogleGenerativeAI(model='gemini-nano', google_api_key= 'secret-api-key') print(chat.google_api_key, end='') captured = capsys.readouterr() assert captured.out == '**********'
def test_api_key_masked_when_passed_via_constructor(capsys: CaptureFixture ) ->None: chat = ChatGoogleGenerativeAI(model='gemini-nano', google_api_key= 'secret-api-key') print(chat.google_api_key, end='') captured = capsys.readouterr() assert captured.out == '**********'
null
test_refresh_schema
mock_client.return_value = MagicMock() huge_graph = HugeGraph(self.username, self.password, self.address, self. port, self.graph) huge_graph.refresh_schema() self.assertNotEqual(huge_graph.get_schema, '')
@patch('hugegraph.connection.PyHugeGraph') def test_refresh_schema(self, mock_client: Any) ->None: mock_client.return_value = MagicMock() huge_graph = HugeGraph(self.username, self.password, self.address, self .port, self.graph) huge_graph.refresh_schema() self.assertNotEqual(huge_graph.get_sche...
null