-
Notifications
You must be signed in to change notification settings - Fork 183
feat: Support citation for agentic template #642
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 13 commits
Commits
Show all changes
29 commits
Select commit
Hold shift + click to select a range
ec06a12
feat: add citation processing and prompts for query engine
leehuwuj ff9acac
add example and improve tool description
leehuwuj a46d655
better cond
leehuwuj ad0c2f3
Improve citation instructions in prompts and enhance logging in query…
leehuwuj 0960b14
Merge remote-tracking branch 'origin/main' into lee/citation-agentic
leehuwuj 491dd8e
Enhance citation instructions in prompts, improve error handling in s…
leehuwuj 22ca4ba
Update @llamaindex/chat-ui to version 0.4.6 in package.json and pnpm-…
leehuwuj eedffb0
Enhance system prompt and tool description for improved clarity on kn…
leehuwuj 13a1454
introduce preconfigured agent for citation answering
leehuwuj 8799669
Refactor workflow creation to utilize query tool with citation suppor…
leehuwuj fd82563
Implement AgentCallTool for event handling in chat router; enhance to…
leehuwuj 7a463d0
better display llamacloud file name
leehuwuj f6f5f23
Merge remote-tracking branch 'origin/main' into lee/citation-agentic
leehuwuj 1c83fa2
Remove citation agent implementation and update dependencies in pypro…
leehuwuj 7a33a58
update createllama and add changesets
leehuwuj 3a2be5c
Refactor citation handling in query tools
leehuwuj 641a2be
Refactor SourceNodesFromToolCall initialization to use optional tool_…
leehuwuj 46dec12
Refactor query engine and citation handling; enable citation in workf…
leehuwuj b95dcc7
refactor llamacloud file
leehuwuj b73680f
Refactor SourceNodesFromToolCall to remove deprecated tool_name param…
leehuwuj 31576d9
fix mypy
leehuwuj 356bbb3
add test for local python package
leehuwuj e6e2f78
remove tool name constraint
leehuwuj f9f3437
add missing working-directory
leehuwuj 0ad7581
Update e2e workflow to build server package and set SERVER_PACKAGE_PA…
leehuwuj c3ad902
Update dependency handling for llama-index-server template in CI; rem…
leehuwuj c32b7f3
config hatch to fix script
leehuwuj f7c4ed3
fix mkdir windows
leehuwuj 8764d93
fix wrong build command
leehuwuj File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
import os | ||
from typing import Optional | ||
|
||
from fastapi import FastAPI | ||
from llama_index.core.agent.workflow import AgentWorkflow | ||
from llama_index.core.settings import Settings | ||
from llama_index.llms.openai import OpenAI | ||
from llama_index.server import LlamaIndexServer, UIConfig | ||
from llama_index.server.api.models import ChatRequest | ||
from llama_index.server.services.llamacloud import get_index | ||
from llama_index.server.tools.index.query import get_query_engine_tool | ||
|
||
# Please set the following environment variables to use LlamaCloud | ||
if os.getenv("LLAMA_CLOUD_API_KEY") is None: | ||
raise ValueError("LLAMA_CLOUD_API_KEY is not set") | ||
if os.getenv("LLAMA_CLOUD_PROJECT_NAME") is None: | ||
raise ValueError("LLAMA_CLOUD_PROJECT_NAME is not set") | ||
if os.getenv("LLAMA_CLOUD_INDEX_NAME") is None: | ||
raise ValueError("LLAMA_CLOUD_INDEX_NAME is not set") | ||
|
||
Settings.llm = OpenAI(model="gpt-4.1") | ||
|
||
|
||
def create_workflow(chat_request: Optional[ChatRequest] = None) -> AgentWorkflow: | ||
index = get_index(chat_request=chat_request) | ||
if index is None: | ||
raise RuntimeError("Index not found!") | ||
# Create a query tool with citations enabled | ||
query_tool = get_query_engine_tool(index=index, enable_citation=True) | ||
|
||
# Append the citation system prompt to the system prompt | ||
system_prompt = """ | ||
You are a helpful assistant that has access to a knowledge base. | ||
""" | ||
system_prompt += query_tool.citation_system_prompt | ||
return AgentWorkflow.from_tools_or_functions( | ||
tools_or_functions=[query_tool], | ||
system_prompt=system_prompt, | ||
) | ||
|
||
|
||
def create_app() -> FastAPI: | ||
app = LlamaIndexServer( | ||
workflow_factory=create_workflow, | ||
env="dev", | ||
suggest_next_questions=False, | ||
ui_config=UIConfig( | ||
llamacloud_index_selector=True, # to select different indexes in the UI | ||
), | ||
) | ||
return app | ||
|
||
|
||
app = create_app() | ||
|
||
|
||
if __name__ == "__main__": | ||
import uvicorn | ||
|
||
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
26 changes: 26 additions & 0 deletions
26
python/llama-index-server/llama_index/server/api/callbacks/agent_call_tool.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
import logging | ||
from typing import Any | ||
|
||
from llama_index.core.agent.workflow.workflow_events import ToolCall, ToolCallResult | ||
from llama_index.server.api.callbacks.base import EventCallback | ||
from llama_index.server.api.models import AgentRunEvent | ||
|
||
logger = logging.getLogger("uvicorn") | ||
|
||
|
||
class AgentCallTool(EventCallback): | ||
""" | ||
Adapter for convert tool call events to agent run events. | ||
""" | ||
|
||
async def run(self, event: Any) -> Any: | ||
if isinstance(event, ToolCall) and not isinstance(event, ToolCallResult): | ||
return AgentRunEvent( | ||
name="Agent", | ||
msg=f"Calling tool: {event.tool_name} with: {event.tool_kwargs}", | ||
) | ||
return event | ||
|
||
@classmethod | ||
def from_default(cls, *args: Any, **kwargs: Any) -> "AgentCallTool": | ||
return cls() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
3 changes: 2 additions & 1 deletion
3
python/llama-index-server/llama_index/server/tools/index/__init__.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,4 @@ | ||
from .query import get_query_engine_tool | ||
from .node_citation_processor import NodeCitationProcessor | ||
|
||
__all__ = ["get_query_engine_tool"] | ||
__all__ = ["get_query_engine_tool", "NodeCitationProcessor"] |
46 changes: 46 additions & 0 deletions
46
python/llama-index-server/llama_index/server/tools/index/citation_agent.py
leehuwuj marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
from typing import Optional | ||
|
||
from llama_index.core.agent.workflow import FunctionAgent, ReActAgent | ||
from llama_index.core.llms import LLM | ||
from llama_index.core.settings import Settings | ||
from llama_index.server.tools.index import get_query_engine_tool | ||
|
||
|
||
def create_citation_agent( | ||
index, | ||
llm: Optional[LLM] = None, | ||
name: Optional[str] = None, | ||
description: Optional[str] = None, | ||
system_prompt: Optional[str] = None, | ||
) -> FunctionAgent | ReActAgent: | ||
leehuwuj marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" | ||
Create a citation agent that can answer question with citations using information from provided index. | ||
Example: | ||
```python | ||
citation_agent = create_citation_agent(index=index) | ||
my_workflow = AgentWorkflow(agents=[citation_agent], root_agent=citation_agent.name) | ||
my_workflow.run(user_msg="Why is sky blue?") | ||
``` | ||
""" | ||
llm = llm or Settings.llm | ||
agent_cls = FunctionAgent if llm.metadata.is_function_calling_model else ReActAgent | ||
name = name or "citation_agent" | ||
description = ( | ||
description | ||
or "An agent that can answer questions with citations using information from provided index. Do not change the citations when restructuring the answer." | ||
) | ||
system_prompt = ( | ||
system_prompt | ||
or """ | ||
You are a helpful assistant that have access to a knowledge base. | ||
You can use the query_index tool to get the information you need. | ||
Answer the user question with citations for the parts that uses the information from the knowledge base. | ||
""" | ||
) | ||
return agent_cls( | ||
name=name, | ||
description=description, | ||
tools=[get_query_engine_tool(index=index, enable_citation=True)], | ||
llm=llm or Settings.llm, | ||
system_prompt=system_prompt, | ||
) | ||
leehuwuj marked this conversation as resolved.
Show resolved
Hide resolved
|
21 changes: 21 additions & 0 deletions
21
python/llama-index-server/llama_index/server/tools/index/node_citation_processor.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
from typing import List, Optional | ||
|
||
from llama_index.core import QueryBundle | ||
from llama_index.core.postprocessor.types import BaseNodePostprocessor | ||
from llama_index.core.schema import NodeWithScore | ||
|
||
|
||
class NodeCitationProcessor(BaseNodePostprocessor): | ||
""" | ||
Add a new field `citation_id` to the metadata of the node by copying the id from the node. | ||
Useful for citation construction. | ||
""" | ||
|
||
def _postprocess_nodes( | ||
self, | ||
nodes: List[NodeWithScore], | ||
query_bundle: Optional[QueryBundle] = None, | ||
) -> List[NodeWithScore]: | ||
for node_score in nodes: | ||
node_score.node.metadata["citation_id"] = node_score.node.node_id | ||
return nodes |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.