ChickenBenny commented on code in PR #1389: URL: https://github.com/apache/flink-agents/pull/1389#discussion_r4584075274
########## python/flink_agents/api/tools/vector_store_search_tool.py: ########## @@ -0,0 +1,149 @@ +################################################################################ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +################################################################################# +"""Built-in tool that lets an agent search a registered vector store.""" + +import base64 +import datetime +import math +from typing import Any, Dict, List + +from pydantic import BaseModel, Field, model_validator +from typing_extensions import override + +from flink_agents.api.resource import ResourceType +from flink_agents.api.tools.tool import Tool, ToolMetadata, ToolType +from flink_agents.api.vector_stores.vector_store import VectorStoreQuery + +NO_RESULTS_MESSAGE = "No relevant documents found." + + +class VectorStoreSearchArgs(BaseModel): + """Arguments of VectorStoreSearchTool that are visible to the model.""" + + query: str = Field( + ..., + description="Natural-language query describing the information to find.", + ) + + +class VectorStoreSearchTool(Tool): + """Search a vector store declared in the same agent. + + The model passes only ``query``. The tool returns a list of + ``{"content": ..., "metadata": ...}`` entries, with metadata converted to + JSON-compatible values, or ``"No relevant documents found."``. Errors from + the vector store are raised, not returned. + + Register the tool under the same name as its ``name`` argument:: + + agents_env.add_resource( + "search_flink_docs", + ResourceType.TOOL, + VectorStoreSearchTool( + name="search_flink_docs", + description="Search the Flink documentation.", + vector_store="knowledge_base", + max_results=3, + ), + ) + + Attributes: + ---------- + vector_store : str + Name of the vector store resource to search. + max_results : int + Maximum number of documents returned per call. Must be positive. + """ + + vector_store: str + max_results: int = Field(default=3, gt=0) + + @model_validator(mode="before") + @classmethod + def _build_metadata(cls, data: Any) -> Any: + """Build the tool metadata from ``name`` and ``description``. + + A serialized tool already carries ``metadata`` and is passed through. + """ + if not isinstance(data, dict): + return data + if "metadata" in data: + if "name" in data or "description" in data: + msg = ( + "VectorStoreSearchTool accepts either 'metadata' or " + "'name' and 'description', not both." + ) + raise ValueError(msg) + return data + missing = [field for field in ("name", "description") if field not in data] + if missing: + msg = f"VectorStoreSearchTool requires {' and '.join(missing)}." + raise ValueError(msg) + data = dict(data) + data["metadata"] = ToolMetadata( + name=data.pop("name"), + description=data.pop("description"), + args_schema=VectorStoreSearchArgs, + ) + return data + + @classmethod + @override + def tool_type(cls) -> ToolType: + """Return tool type of class.""" + return ToolType.FUNCTION + + @override + def call(self, *args: Any, **kwargs: Any) -> List[Dict[str, Any]] | str: + """Search the vector store and return the matching documents.""" + parsed = ( + VectorStoreSearchArgs(query=args[0], **kwargs) + if args + else VectorStoreSearchArgs(**kwargs) + ) + store = self.resource_context.get_resource( + self.vector_store, ResourceType.VECTOR_STORE + ) Review Comment: Thanks! The tool now resolves the vector store in `open()` and keeps it in a private `_resolved_store`, following `BaseChatModelSetup` and `BaseDecisionModelSetup`. `call()` no longer touches the resource cache, and it raises `TypeError` if the tool hasn't been opened. I added `runtime/tests/test_vector_store_search_tool_concurrency.py`. It sends two concurrent first calls through a real `ResourceCache` and asserts that the store is opened and closed exactly once. On the previous commit it fails with two opens. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
