🦜️🔗 LangChain AgensGraph
LangChain integration for AgensGraph, Skai's PostgreSQL-based graph database: a graph store, a vector store and its retrievers, a Cypher QA chain, an LLM graph transformer, chat message history, and a LangGraph checkpointer and store. Every class works blocking and awaiting.
Requirements
-
Python 3.11 to 3.14.
-
AgensGraph 2.14.1 or later (2.14, 2.15, 2.16, 2.17 and 2.18 are tested).
-
The
vectorextension (pgvector 0.8.0 or later) for the vector store and the store's semantic search. AgensGraph does not bundle it; build it against your server'spg_config:git clone https://github.com/pgvector/pgvector.git cd pgvector && PG_CONFIG=/path/to/agens/bin/pg_config make && make install # then, in the database: CREATE EXTENSION vector;
Installation
pip install -U langchain-agensgraph
pip install -U "langchain-agensgraph[langgraph]" # the checkpointer and the store
Connecting
One AgensEngine per process holds the connection pools; every component takes it, or a conninfo
string, and a graph name. Components handed the same conninfo string share one engine. Nothing
connects until the first call, and each component makes what it needs on that call.
from langchain_agensgraph import AgensEngine, AgensGraph
engine = AgensEngine("postgresql://app_rw:secret@localhost:5432/db")
graph = AgensGraph(engine, graph_name="kg", create_graph=True)
graph.query("MATCH (n) RETURN count(*) AS n")
A component's tables live in the graph's companion schema, "<graph>_store".
Roles
langchain_agensgraph.roles prints the SQL for the roles the package expects:
from langchain_agensgraph.roles import render_grants, render_roles
print(render_roles(password="...")) # app_rw, llm_ro and llm_rw, once per server
print(render_grants("kg")) # what each role may do on one graph, as its owner
app_rwruns the application.llm_roruns Cypher a model wrote. It reads the graph and nothing else.llm_rwruns model-written writes (allow_writes=True), on 2.16 and later only.
Give the engine those roles' conninfo strings:
engine = AgensEngine(
"postgresql://app_rw:secret@localhost/db",
untrusted_conninfo="postgresql://llm_ro:secret@localhost/db",
)
The graph store
graph.query("MATCH (p:\"Person\") WHERE p.age > %s RETURN p.name AS name", (30,))
graph.query_many(["CREATE (:\"Tag\" {name: 'a'})", "CREATE (:\"Tag\" {name: 'b'})"]) # all or none
graph.add_graph_documents(documents, include_source=True, baseEntityLabel=True)
print(graph.get_schema)
- Rows hold the driver's
Vertex,EdgeandPathvalues;sanitize=Truegives plain maps and leaves out lists longer than 128 items. - A server refusal raises
AgensQueryErrorcarrying itssqlstate. - The schema is read on first use and kept for
schema_cache_ttlseconds. Its counts are the planner's estimates. add_graph_documentsmerges each node byid, and each edge once per pair of ends (dedupe_edges=True).query_untrusted(text)runs Cypher a model wrote, asllm_ro. The text is checked before it is sent and refused unless it is plainly one Cypher read. It then runs in a read-only transaction that is always rolled back, reading at mostmax_rowsrows.
The vector store
Each chunk is a vertex. Its embedding is a row of a table in "<graph>_store", deleted with the
vertex.
from langchain_agensgraph import AgensgraphVector
from langchain_agensgraph.vectorstores import KeywordConfig
store = AgensgraphVector(
embeddings,
engine=engine,
graph_name="kg",
label="Chunk",
filter_keys=("source", "year"), # indexed for filtered search
keyword=KeywordConfig(regconfig="english"),
search_type="hybrid", # vector and keyword, fused
create_graph=True,
)
store.add_documents(docs, ids=ids)
store.similarity_search("what failed?", k=5, filter={"year": {"$gte": 2024}})
store.similarity_search_with_relevance_scores("what failed?", k=5)
store.max_marginal_relevance_search("what failed?", k=5, fetch_k=20)
store.delete(ids=["a"])
- The approximate index (HNSW by default, or IVFFlat) is built after the first write. Before then, and for a role that does not own the table, search is exact.
- Filters take
$eq,$ne,$lt,$lte,$gt,$gte,$in,$nin,$between,$like,$ilike,$exists,$and,$orand$not. *_with_scorereturns the distance;*_with_relevance_scoresturns it into a relevance score. In hybrid mode both return the fused score;hybrid_search_with_detailsreturns each half.- Embeddings of up to 2,000 dimensions are stored as
vector, wider ones ashalfvec.
Retrievers
from langchain_agensgraph import (
AgensGraphContextRetriever,
AgensText2CypherRetriever,
AgensVectorRetriever,
)
from langchain_agensgraph.retrievers import render_graph_context
AgensVectorRetriever(vectorstore=store, k=6)
AgensGraphContextRetriever(
vectorstore=store, k=4, hops=2, document_formatter=render_graph_context
)
AgensText2CypherRetriever(graph=graph, llm=llm, allow_dangerous_requests=True)
AgensVectorRetrievertakes aretrieval_query, Cypher that shapes each hit; it seesnodeandscore.AgensGraphContextRetrieveradds each hit's neighbourhood, withinhopsedges, to its metadata.- A call may pass
k=and other search arguments; they win over the retriever's own.
Questions in plain language
from langchain_agensgraph import AgensCypherQAChain, create_cypher_tool
chain = AgensCypherQAChain.from_llm(llm, graph=graph, allow_dangerous_requests=True)
chain.invoke({"query": "Who works at Acme?"}) # {"query": ..., "result": "Ada and Bob."}
tool = create_cypher_tool(graph, llm, allow_dangerous_requests=True)
The model's Cypher runs only through query_untrusted, as llm_ro. Before it is sent:
- the names the graph stores with capitals are quoted;
- an edge written against the only direction the schema has is turned round;
- the forms a release reads wrongly are rewritten.
A refusal, or a server error about the statement, goes back to the model, up to max_retries
times. The prompt carries the rules of the server it runs on. examples=DIALECT_EXAMPLES adds
few-shot pairs. allow_writes=True runs model writes as llm_rw on 2.16 and later.
Extracting a graph from text
from langchain_agensgraph import LLMGraphTransformer
transformer = LLMGraphTransformer(
llm,
allowed_nodes=["Person", "Company"],
allowed_relationships=[("Person", "WORKS_AT", "Company")],
node_properties=["role"],
)
graph.add_graph_documents(transformer.convert_to_graph_documents(docs), include_source=True)
A model without structured output answers in JSON instead (ignore_tool_usage=True forces it).
Chat history, checkpoints and memory
from langchain_agensgraph import AgensChatMessageHistory, AgensSaver, AgensStore
history = AgensChatMessageHistory("session-1", engine, graph_name="kg")
saver = AgensSaver(engine, graph_name="kg") # sync and async graphs alike
store = AgensStore(engine, graph_name="kg", index={"dims": 1536, "embed": embeddings})
app = builder.compile(checkpointer=saver, store=store)
AsyncAgensStore is the store for an event loop. All three keep their state in plain tables in
"<graph>_store".
Agent state next to the graph
Each of them gives a SQL subquery a Cypher statement can hold, so one statement reads the agent's state and the knowledge graph together:
graph.query(
f"UNWIND [1] AS a WITH {history.cypher_subquery()} AS messages "
"UNWIND messages AS m MATCH (p:\"Person\") WHERE m.text CONTAINS p.name "
"RETURN p.name AS who, m.seq AS seq",
(history.session_id,),
)
store.cypher_subquery() gives the items in a namespace. For the checkpointer, declare the
channels to read: AgensSaver(..., queryable_channels={"messages": "messages"}), then use
saver.cypher_subquery("messages").
Transactions
Calls through an engine join a transaction the caller opens:
with engine.transaction() as conn:
store.add_documents(docs)
graph.add_graph_documents(graph_docs)
conn.execute("...") # statements of your own, in the same transaction
What differs between releases
| 2.14 | 2.15 | 2.16 | 2.17 | 2.18 | |
|---|---|---|---|---|---|
model-written writes (allow_writes) |
no | no | yes | yes | yes |
| deleting a vertex scans every edge label | yes | yes | yes | no | no |
| GQL clauses in the QA prompt | no | no | no | no | yes |
Writing Cypher for AgensGraph
- Quote labels and types with capitals:
(n:"Person"). An unquoted name folds to lower case. - Write edges with brackets,
(a)-[]->(b). AgensGraph reads--as the start of a comment. - Name a variable-length edge,
[r:"KNOWS"*1..3]; an unnamed one is wrong on 2.14 and 2.15. - Before 2.17,
ORDER BYnames a returned alias, andx IN %swith a list parameter fails; useUNWIND. - On 2.14,
collect()keeps nulls and gives null for no rows. id(n) = '3.1'is the fastest lookup. Inside a SQL subquery, read a vertex's properties withproperties(n).- Cast to convert,
n.x::float8;toFloat()andtoInteger()are unreliable.
Upgrading from 0.3
See CHANGELOG.md.
Demos and evals
Runnable demos are under examples/demos/. evals/text2cypher/ scores
generated Cypher by running it.
License
Apache-2.0.
Metadata
Release files for langchain-agensgraph 0.4.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| langchain_agensgraph-0.4.0.tar.gz | 224.4 kB | Without provenance | Details for langchain_agensgraph-0.4.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| langchain_agensgraph-0.4.0-py3-none-any.whl | Python 3 | none | any | Details for langchain_agensgraph-0.4.0-py3-none-any.whl |
Total release size: 362.1 kB
Release files / langchain_agensgraph-0.4.0.tar.gz
| Download URL | langchain_agensgraph-0.4.0.tar.gz |
|---|---|
| Size | 224.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
02046c2f229f51ff646c85f549151ad589ad251739b7b685cbf7820218a9ecaa
|
|
BLAKE2b-256 checksum How to use checksums |
97eb3d043d12b5e92a38617fbfacd37e3e441f74a66c3559b3882a29663bb0bb
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.14.9
|
Release files / langchain_agensgraph-0.4.0-py3-none-any.whl
| Download URL | langchain_agensgraph-0.4.0-py3-none-any.whl |
|---|---|
| Size | 137.7 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
4a2a8300a83b016f1ba54cad069a944e26045c5dbd039d13307b0edaa26bd637
|
|
BLAKE2b-256 checksum How to use checksums |
6f2cc580e9ee438b1d974a53c487a08ef07d1807312aeb57c0a3b8724ca9c41d
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.14.9
|
Security for langchain-agensgraph 0.4.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.