Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
4bec67c
grapgh integration and unit tests
lasyasn May 11, 2025
358394f
Merge branch 'tests' into test_lasya
lasyasn May 19, 2025
11cf59a
tests for graph(integration and unit- 98% each) and graph_qa(integrat…
lasyasn May 28, 2025
9a87e74
Merge branch 'tests' into test_lasya
aMahanna May 30, 2025
84ae7e3
fix: lint PT1
aMahanna May 30, 2025
c493899
Merge branch 'main' into test_lasya
aMahanna May 30, 2025
4193eff
lint tests
SLasyaN Jun 2, 2025
518b83c
remove: AQL_WRITE_OPERATIONS
aMahanna Jun 2, 2025
0ba8ba8
lint changes
SLasyaN Jun 2, 2025
382471b
lint tests
SLasyaN Jun 8, 2025
b97c916
lint tests
SLasyaN Jun 8, 2025
6c0780d
lint tests
SLasyaN Jun 8, 2025
84875b7
lint tests
SLasyaN Jun 8, 2025
9744801
fix: lint
aMahanna Jun 9, 2025
b6f7716
Squashed commit of the following:
aMahanna Jun 9, 2025
e65310a
Revert "Squashed commit of the following:"
aMahanna Jun 9, 2025
e582174
comments addressed except .DS store file removal
SLasyaN Jun 9, 2025
4c02f05
update
SLasyaN Jun 9, 2025
cbf0c97
Merge branch 'test_lasya' into docs_lasya
SLasyaN Jun 9, 2025
3cc52bd
docs update
SLasyaN Jun 11, 2025
402a801
changed docs
SLasyaN Jun 11, 2025
4b781bd
Merge branch 'docs' into docs_lasya
SLasyaN Jun 11, 2025
7bd353a
Warning reolution
SLasyaN Jun 11, 2025
6f334bd
Merge branch 'docs_lasya' of https://github.com/arangoml/langchain-ar…
SLasyaN Jun 11, 2025
2dd6a81
Merge branch 'docs' into docs_lasya
aMahanna Jun 11, 2025
a016992
format
aMahanna Jun 11, 2025
68a596e
Delete .DS_Store
aMahanna Jun 11, 2025
e1e4fb8
cleanup
aMahanna Jun 11, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions libs/arangodb/doc/api_reference.rst
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ Graphs
:undoc-members:
:show-inheritance:


Chains
------

Expand Down
252 changes: 252 additions & 0 deletions libs/arangodb/doc/arangoqachain.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,252 @@
ArangoGraphQAChain
========================

This guide demonstrates how to use the ArangoGraphQAChain for question-answering against an ArangoDB graph database.

Basic Setup
-----------

First, let's set up the necessary imports and create a basic instance:

.. code-block:: python

from langchain_arangodb.chains.graph_qa.arangodb import ArangoGraphQAChain
from langchain_arangodb.graphs.arangodb_graph import ArangoGraph
from langchain.chat_models import ChatOpenAI
from arango import ArangoClient

# Initialize ArangoDB connection
client = ArangoClient()
db = client.db("your_database", username="user", password="pass")

# Create graph instance
graph = ArangoGraph(db)

# Initialize LLM
llm = ChatOpenAI(temperature=0)

# Create the chain
chain = ArangoGraphQAChain.from_llm(
llm=llm,
graph=graph,
allow_dangerous_requests=True # Be cautious with this setting
)

Individual Method Usage
-----------------------

1. Basic Query Execution
~~~~~~~~~~~~~~~~~~~~~~~~

The simplest way to use the chain is with a direct query:

.. code-block:: python

response = chain.invoke({"query": "Who starred in Pulp Fiction?"})
print(response["result"])

2. Using Custom Input/Output Keys
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

You can customize the input and output keys:

.. code-block:: python

chain = ArangoGraphQAChain.from_llm(
llm=llm,
graph=graph,
allow_dangerous_requests=True,
input_key="question",
output_key="answer"
)

response = chain.invoke({"question": "Who directed Inception?"})
print(response["answer"])

3. Limiting Results
~~~~~~~~~~~~~~~~~~~

Control the number of results returned:

.. code-block:: python

chain = ArangoGraphQAChain.from_llm(
llm=llm,
graph=graph,
allow_dangerous_requests=True,
top_k=5, # Return only top 5 results
output_list_limit=16, # Limit list length in response
output_string_limit=128 # Limit string length in response
)

4. Query Explanation Mode
~~~~~~~~~~~~~~~~~~~~~~~~~

Get query explanation without execution:

.. code-block:: python

chain = ArangoGraphQAChain.from_llm(
llm=llm,
graph=graph,
allow_dangerous_requests=True,
execute_aql_query=False # Only explain, don't execute
)

explanation = chain.invoke({"query": "Find all movies released after 2020"})
print(explanation["aql_result"]) # Contains query plan

5. Read-Only Mode
~~~~~~~~~~~~~~~~~

Enforce read-only operations:

.. code-block:: python

chain = ArangoGraphQAChain.from_llm(
llm=llm,
graph=graph,
allow_dangerous_requests=True,
force_read_only_query=True # Prevents write operations
)

6. Custom AQL Examples
~~~~~~~~~~~~~~~~~~~~~~

Provide example AQL queries for better generation:

.. code-block:: python

example_queries = """
FOR m IN Movies
FILTER m.year > 2020
RETURN m.title

FOR a IN Actors
FILTER a.awards > 0
RETURN a.name
"""

chain = ArangoGraphQAChain.from_llm(
llm=llm,
graph=graph,
allow_dangerous_requests=True,
aql_examples=example_queries
)

7. Detailed Output
~~~~~~~~~~~~~~~~~~

Get more detailed output including AQL query and results:

.. code-block:: python

chain = ArangoGraphQAChain.from_llm(
llm=llm,
graph=graph,
allow_dangerous_requests=True,
return_aql_query=True,
return_aql_result=True
)

response = chain.invoke({"query": "Who acted in The Matrix?"})
print("Query:", response["aql_query"])
print("Raw Results:", response["aql_result"])
print("Final Answer:", response["result"])

Complete Workflow Example
-------------------------

Here's a complete workflow showing how to use multiple features together:

.. code-block:: python

from langchain_arangodb.chains.graph_qa.arangodb import ArangoGraphQAChain
from langchain_arangodb.graphs.arangodb_graph import ArangoGraph
from langchain.chat_models import ChatOpenAI
from arango import ArangoClient

# 1. Setup Database Connection
client = ArangoClient()
db = client.db("movies_db", username="user", password="pass")

# 2. Initialize Graph
graph = ArangoGraph(db)

# 3. Create Collections and Sample Data
if not db.has_collection("Movies"):
movies = db.create_collection("Movies")
movies.insert({"_key": "matrix", "title": "The Matrix", "year": 1999})

if not db.has_collection("Actors"):
actors = db.create_collection("Actors")
actors.insert({"_key": "keanu", "name": "Keanu Reeves"})

if not db.has_collection("ActedIn"):
acted_in = db.create_collection("ActedIn", edge=True)
acted_in.insert({
"_from": "Actors/keanu",
"_to": "Movies/matrix"
})

# 4. Refresh Schema
graph.refresh_schema()

# 5. Initialize Chain with Advanced Features
llm = ChatOpenAI(temperature=0)
chain = ArangoGraphQAChain.from_llm(
llm=llm,
graph=graph,
allow_dangerous_requests=True,
top_k=5,
force_read_only_query=True,
return_aql_query=True,
return_aql_result=True,
output_list_limit=20,
output_string_limit=200
)

# 6. Run Multiple Queries
queries = [
"Who acted in The Matrix?",
"What movies were released in 1999?",
"List all actors in the database"
]

for query in queries:
print(f"\nProcessing query: {query}")
response = chain.invoke({"query": query})

print("AQL Query:", response["aql_query"])
print("Raw Results:", response["aql_result"])
print("Final Answer:", response["result"])
print("-" * 50)

Security Considerations
-----------------------

1. Always use appropriate database credentials with minimal required permissions
2. Be cautious with ``allow_dangerous_requests=True``
3. Use ``force_read_only_query=True`` when only read operations are needed
4. Monitor and log query execution in production environments
5. Regularly review and update AQL examples to prevent injection risks

Error Handling
--------------

The chain includes built-in error handling:

.. code-block:: python

try:
response = chain.invoke({"query": "Find all movies"})
except ValueError as e:
if "Maximum amount of AQL Query Generation attempts" in str(e):
print("Failed to generate valid AQL after multiple attempts")
elif "Write operations are not allowed" in str(e):
print("Attempted write operation in read-only mode")
else:
print(f"Other error: {e}")

The chain will automatically attempt to fix invalid AQL queries up to
``max_aql_generation_attempts`` times (default: 3) before raising an error.
16 changes: 8 additions & 8 deletions libs/arangodb/doc/chat_message_histories.rst
Original file line number Diff line number Diff line change
Expand Up @@ -317,11 +317,11 @@ Messages are stored in ArangoDB with the following structure:
- ``time``: Timestamp for message ordering (automatically added by ArangoDB)

Indexing Strategy
~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~

The class automatically creates a persistent index on ``session_id`` to ensure efficient retrieval:

.. code-block:: aql
.. code-block:: python

// Automatic index creation
CREATE INDEX session_idx ON ChatHistory (session_id) OPTIONS {type: "persistent", unique: false}
Expand All @@ -332,7 +332,7 @@ Best Practices
--------------

Session ID Management
~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~

1. **Use descriptive session IDs**: Include user context or conversation type
2. **Avoid special characters**: Stick to alphanumeric characters and underscores
Expand All @@ -346,7 +346,7 @@ Session ID Management
session_id = f"training_{model_version}_{session_counter}"

Memory Management
~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~

1. **Choose appropriate memory types** based on conversation length
2. **Implement session cleanup** for privacy or storage management
Expand All @@ -372,7 +372,7 @@ Memory Management
db.aql.execute(query, bind_vars=bind_vars)

Error Handling
~~~~~~~~~~~~~
~~~~~~~~~~~~~~

.. code-block:: python

Expand All @@ -396,15 +396,15 @@ Error Handling
print(f"Unexpected error: {e}")

Performance Considerations
-------------------------
--------------------------

1. **Session ID indexing**: Automatic indexing ensures O(log n) lookup performance
2. **Message ordering**: Uses ArangoDB's built-in sorting capabilities
3. **Batch operations**: Consider bulk operations for high-volume scenarios
4. **Collection sizing**: Monitor and archive old conversations as needed

Example: Complete Chat Application
---------------------------------
----------------------------------

.. code-block:: python

Expand Down Expand Up @@ -506,7 +506,7 @@ Troubleshooting
---------------

Common Issues
~~~~~~~~~~~~
~~~~~~~~~~~~~

**ValueError: Please ensure that the session_id parameter is provided**
- Ensure session_id is not None, empty string, or 0
Expand Down
14 changes: 7 additions & 7 deletions libs/arangodb/doc/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@

sys.path.insert(0, os.path.abspath(".."))

project = 'langchain-arangodb'
copyright = '2025, ArangoDB'
author = 'ArangoDB'
project = "langchain-arangodb"
copyright = "2025, ArangoDB"
author = "ArangoDB"

# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
Expand All @@ -25,15 +25,15 @@
"sphinx.ext.autosummary",
"sphinx.ext.inheritance_diagram",
]
templates_path = ['_templates']
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
templates_path = ["_templates"]
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]


# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output

html_theme = 'sphinx_rtd_theme'
html_static_path = [] # ['_static']
html_theme = "sphinx_rtd_theme"
html_static_path = [] # type: ignore
autodoc_member_order = "bysource"
autodoc_inherit_docstrings = True
autosummary_generate = True
Expand Down
Loading