from typing import List, Optional, Union
from langchain_core.output_parsers import PydanticToolsParser
from langchain_core.tools import StructuredTool, tool
from langchain_openai import ChatOpenAI
def retrieve(
query: str,
itemType: Optional[str],
tag: Optional[Union[str, List[str]]],
qmode: str = "everything",
since: Optional[int] = None,
):
retrieved_docs = retriever.invoke(
query, itemType=itemType, tag=tag, qmode=qmode, since=since
)
serialized_docs = "\n\n".join(
(
f"Metadata: { {key: doc.metadata[key] for key in doc.metadata if key != 'abstractNote'} }\n"
f"Abstract: {doc.metadata['abstractNote']}\n"
)
for doc in retrieved_docs
)
return serialized_docs, retrieved_docs
description = """Search and return relevant documents from a Zotero library. The following search parameters can be used:
Args:
query: str: The search query to be used. Try to keep this specific and short, e.g. a specific topic or author name
itemType: Optional. Type of item to search for (e.g. "book" or "journalArticle"). Multiple types can be passed as a string separated by "||", e.g. "book || journalArticle". Defaults to all types.
tag: Optional. For searching over tags attached to library items. If documents tagged with multiple tags are to be retrieved, pass them as a list. If documents with any of the tags are to be retrieved, pass them as a string separated by "||", e.g. "tag1 || tag2"
qmode: Search mode to use. Changes what the query searches over. "everything" includes full-text content. "titleCreatorYear" to search over title, authors and year. Defaults to "everything".
since: Return only objects modified after the specified library version. Defaults to return everything.
"""
retriever_tool = StructuredTool.from_function(
func=retrieve,
name="retrieve",
description=description,
return_direct=True,
)
llm = ChatOpenAI(model="gpt-4o-mini-2024-07-18")
llm_with_tools = llm.bind_tools([retrieve])
q = "What journal articles do I have on Surveillance in the zotero library?"
chain = llm_with_tools | PydanticToolsParser(tools=[retrieve])
chain.invoke(q)