WARNING: THIS SITE IS A MIRROR OF GITHUB.COM / IT CANNOT LOGIN OR REGISTER ACCOUNTS / THE CONTENTS ARE PROVIDED AS-IS / THIS SITE ASSUMES NO RESPONSIBILITY FOR ANY DISPLAYED CONTENT OR LINKS / IF YOU FOUND SOMETHING MAY NOT GOOD FOR EVERYONE, CONTACT ADMIN AT ilovescratch@foxmail.com
Skip to content

Commit 89a8236

Browse files
authored
Merge branch 'main' into mm_func_call
2 parents c5c8ead + 84066b1 commit 89a8236

File tree

6 files changed

+623
-1
lines changed

6 files changed

+623
-1
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
# This workflow will install Python dependencies, run tests and lint with a variety of Python versions
2+
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions
3+
4+
name: ContribGraphRagTests
5+
6+
on:
7+
pull_request:
8+
branches: ["main"]
9+
paths:
10+
- "autogen/agentchat/contrib/graph_rag/**"
11+
- "test/agentchat/contrib/graph_rag/**"
12+
- ".github/workflows/contrib-tests.yml"
13+
- "setup.py"
14+
15+
concurrency:
16+
group: ${{ github.workflow }}-${{ github.ref }}-${{ github.head_ref }}
17+
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
18+
permissions:
19+
{}
20+
# actions: read
21+
# checks: read
22+
# contents: read
23+
# deployments: read
24+
jobs:
25+
GraphRagIntegrationTest-FalkorDB-Ubuntu:
26+
runs-on: ubuntu-latest
27+
strategy:
28+
fail-fast: false
29+
matrix:
30+
python-version: ["3.10", "3.11"]
31+
services:
32+
falkordb:
33+
image: falkordb/falkordb:edge
34+
ports:
35+
- 6379:6379
36+
steps:
37+
- uses: actions/checkout@v4
38+
- name: Set up Python ${{ matrix.python-version }}
39+
uses: actions/setup-python@v5
40+
with:
41+
python-version: ${{ matrix.python-version }}
42+
- name: Install packages and dependencies for all tests
43+
run: |
44+
python -m pip install --upgrade pip wheel
45+
pip install pytest
46+
- name: Install Falkor DB SDK when on linux
47+
run: |
48+
pip install -e .[graph_rag_falkor_db]
49+
- name: Set AUTOGEN_USE_DOCKER based on OS
50+
shell: bash
51+
run: |
52+
echo "AUTOGEN_USE_DOCKER=False" >> $GITHUB_ENV
53+
- name: Coverage
54+
env:
55+
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
56+
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
57+
AZURE_OPENAI_API_BASE: ${{ secrets.AZURE_OPENAI_API_BASE }}
58+
OAI_CONFIG_LIST: ${{ secrets.OAI_CONFIG_LIST }}
59+
run: |
60+
pip install pytest-cov>=5
61+
pytest test/agentchat/contrib/graph_rag/test_falkor_graph_rag.py --skip-openai
62+
- name: Upload coverage to Codecov
63+
uses: codecov/codecov-action@v3
64+
with:
65+
file: ./coverage.xml
66+
flags: unittests
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
import os
2+
from dataclasses import field
3+
from typing import List
4+
5+
from graphrag_sdk import KnowledgeGraph, Source
6+
from graphrag_sdk.schema import Schema
7+
8+
from .document import Document
9+
from .graph_query_engine import GraphStoreQueryResult
10+
11+
12+
class FalkorGraphQueryResult(GraphStoreQueryResult):
13+
messages: list = field(default_factory=list)
14+
15+
16+
class FalkorGraphQueryEngine:
17+
"""
18+
This is a wrapper for Falkor DB KnowledgeGraph.
19+
"""
20+
21+
def __init__(
22+
self,
23+
name: str,
24+
host: str = "127.0.0.1",
25+
port: int = 6379,
26+
username: str | None = None,
27+
password: str | None = None,
28+
model: str = "gpt-4-1106-preview",
29+
schema: Schema | None = None,
30+
):
31+
"""
32+
Initialize a Falkor DB knowledge graph.
33+
Please also refer to https://github.com/FalkorDB/GraphRAG-SDK/blob/main/graphrag_sdk/kg.py
34+
35+
Args:
36+
name (str): Knowledge graph name.
37+
host (str): FalkorDB hostname.
38+
port (int): FalkorDB port number.
39+
username (str|None): FalkorDB username.
40+
password (str|None): FalkorDB password.
41+
model (str): OpenAI model to use for Falkor DB to build and retrieve from the graph.
42+
schema: Falkor DB knowledge graph schema (ontology), https://github.com/FalkorDB/GraphRAG-SDK/blob/main/graphrag_sdk/schema/schema.py
43+
If None, Falkor DB will auto generate a schema from the input docs.
44+
"""
45+
self.knowledge_graph = KnowledgeGraph(name, host, port, username, password, model, schema)
46+
47+
def init_db(self, input_doc: List[Document] | None):
48+
"""
49+
Build the knowledge graph with input documents.
50+
"""
51+
sources = []
52+
for doc in input_doc:
53+
if os.path.exists(doc.path_or_url):
54+
sources.append(Source(doc.path_or_url))
55+
56+
if sources:
57+
self.knowledge_graph.process_sources(sources)
58+
59+
def add_records(self, new_records: List) -> bool:
60+
raise NotImplementedError("This method is not supported by Falkor DB SDK yet.")
61+
62+
def query(self, question: str, n_results: int = 1, **kwargs) -> FalkorGraphQueryResult:
63+
"""
64+
Query the knowledage graph with a question and optional message history.
65+
66+
Args:
67+
question: a human input question.
68+
n_results: number of returned results.
69+
kwargs:
70+
messages: a list of message history.
71+
72+
Returns: FalkorGraphQueryResult
73+
"""
74+
messages = kwargs.pop("messages", [])
75+
answer, messages = self.knowledge_graph.ask(question, messages)
76+
return FalkorGraphQueryResult(answer=answer, results=[], messages=messages)

autogen/agentchat/contrib/graph_rag/graph_query_engine.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,6 @@ def init_db(self, input_doc: List[Document] | None = None):
3434
Args:
3535
input_doc: a list of input documents that are used to build the graph in database.
3636
37-
Returns: GraphStore
3837
"""
3938
pass
4039

setup.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,10 @@
5959

6060
retrieve_chat_pgvector = [*retrieve_chat, "pgvector>=0.2.5"]
6161

62+
graph_rag_falkor_db = [
63+
"graphrag_sdk",
64+
]
65+
6266
if current_os in ["Windows", "Darwin"]:
6367
retrieve_chat_pgvector.extend(["psycopg[binary]>=3.1.18"])
6468
elif current_os == "Linux":
@@ -81,6 +85,7 @@
8185
"retrievechat-pgvector": retrieve_chat_pgvector,
8286
"retrievechat-mongodb": [*retrieve_chat, "pymongo>=4.0.0"],
8387
"retrievechat-qdrant": [*retrieve_chat, "qdrant_client", "fastembed>=0.3.1"],
88+
"graph_rag_falkor_db": graph_rag_falkor_db,
8489
"autobuild": ["chromadb", "sentence-transformers", "huggingface-hub", "pysqlite3"],
8590
"teachable": ["chromadb"],
8691
"lmm": ["replicate", "pillow"],
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import sys
2+
3+
import pytest
4+
from conftest import reason, skip_openai # noqa: E402
5+
from graphrag_sdk import KnowledgeGraph, Source
6+
from graphrag_sdk.schema import Schema
7+
8+
try:
9+
from autogen.agentchat.contrib.graph_rag.document import (
10+
Document,
11+
DocumentType,
12+
)
13+
from autogen.agentchat.contrib.graph_rag.falkor_graph_query_engine import (
14+
FalkorGraphQueryEngine,
15+
GraphStoreQueryResult,
16+
)
17+
except ImportError:
18+
skip = True
19+
else:
20+
skip = False
21+
22+
reason = "do not run on MacOS or windows OR dependency is not installed OR " + reason
23+
24+
25+
@pytest.mark.skipif(
26+
sys.platform in ["darwin", "win32"] or skip or skip_openai,
27+
reason=reason,
28+
)
29+
def test_falkor_db_query_engine():
30+
"""
31+
Test Falkor DB Query Engine.
32+
1. create a test Falkor DB Query Engine with a schema.
33+
2. Initialize it with an input txt file.
34+
3. Query it with a question and verify the result contains the critical information.
35+
"""
36+
# Arrange
37+
test_schema = Schema()
38+
actor = test_schema.add_entity("Actor").add_attribute("name", str, unique=True)
39+
movie = test_schema.add_entity("Movie").add_attribute("title", str, unique=True)
40+
test_schema.add_relation("ACTED", actor, movie)
41+
42+
query_engine = FalkorGraphQueryEngine(schema=test_schema)
43+
44+
source_file = "test/agentchat/contrib/graph_rag/the_matrix.txt"
45+
input_docs = [Document(doctype=DocumentType.TEXT, path_or_url=source_file)]
46+
47+
question = "Name a few actors who've played in 'The Matrix'"
48+
49+
# Act
50+
query_engine.init_db(input_doc=input_docs)
51+
52+
query_result: GraphStoreQueryResult = query_engine.query(question=question)
53+
54+
# Assert
55+
assert query_result.answer.find("Keanu Reeves") >= 0
56+
for message in query_result.messages:
57+
if isinstance(message, dict) and "role" in message and message["role"] == "user":
58+
assert "content" in message
59+
assert message["content"] is question
60+
return
61+
pytest.fail("Question not found in message history.")

0 commit comments

Comments
 (0)