Simple LightRAG API client for Python.
This library provides both synchronous and asynchronous clients for interacting with the LightRAG API, enabling document management, RAG queries, knowledge graph operations, and more.
Install from source using uv or pip:
# Using uv
uv add lightrag-api
# Using pip
pip install lightrag-apiRequirements:
- π Python >= 3.10
- π‘ httpx >= 0.28.1
- β pydantic >= 2.12.5
from lightrag.api import SyncLightRagClient
# Initialize client with API key
client = SyncLightRagClient(
base_url="https://your-lightrag-server.com",
api_key="your-api-key"
)
# Execute a query
response = client.query("What is machine learning?")
print(response.response)
# Don't forget to close the client
client.close()from lightrag.api import AsyncLightRagClient
async def main():
# Initialize client with OAuth token
client = AsyncLightRagClient(
base_url="https://your-lightrag-server.com",
oauth_token="your-oauth-token"
)
try:
# Execute a query
response = await client.query("What is machine learning?")
print(response.response)
finally:
await client.close()
# Run the async function
import asyncio
asyncio.run(main())- π Document Management: Upload documents, insert text, delete documents, and manage document pipelines
- π RAG Queries: Execute queries with multiple modes (local, global, hybrid, naive, mix, bypass), streaming support, and conversation history
- πΈοΈ Knowledge Graph Operations: Create, update, merge, and delete entities and relations
- βοΈ Pipeline Management: Monitor and control document processing pipelines
- π Dual Client Support: Both synchronous (
SyncLightRagClient) and asynchronous (AsyncLightRagClient) clients - π‘οΈ Type Safety: Full Pydantic model support for request/response validation
from lightrag.api import SyncLightRagClient, AsyncLightRagClient
# Sync client with API key
sync_client = SyncLightRagClient(
base_url="https://api.example.com",
api_key="your-api-key"
)
# Async client with OAuth token
async_client = AsyncLightRagClient(
base_url="https://api.example.com",
oauth_token="your-oauth-token"
)# Synchronous query
response = sync_client.query(
query="Explain quantum computing",
mode="mix",
include_references=True
)
print(response.response)
print(response.references)
# Asynchronous query
response = await async_client.query(
query="Explain quantum computing",
mode="mix",
include_references=True
)# Upload a file
response = sync_client.upload_document("path/to/document.pdf")
print(f"Document ID: {response.doc_id}")
# Or upload from bytes
with open("document.pdf", "rb") as f:
response = sync_client.upload_document(f.read())# Insert single text
response = sync_client.insert_text(
text="Your document content here...",
file_source="manual_input.txt"
)
# Insert multiple texts
response = sync_client.insert_texts(
texts=["Text 1", "Text 2", "Text 3"],
file_sources=["doc1.txt", "doc2.txt", "doc3.txt"]
)upload_document(file)- Upload a document fileinsert_text(text, file_source)- Insert text into the systeminsert_texts(texts, file_sources)- Insert multiple textsget_documents()- Get statuses of all documentsget_documents_paginated(page, page_size)- Get paginated document listdelete_document(doc_ids, delete_file, delete_llm_cache)- Delete documents by IDclear_documents()- Clear all documentsget_pipeline_status()- Get document processing pipeline statuscancel_pipeline()- Cancel current processing pipelinereprocess_failed()- Reprocess failed documentsget_status_counts()- Get document status countsget_track_status(track_id)- Track document processing statusscan_documents()- Scan for new documents
query(query, mode, include_references, ...)- Execute RAG queryquery_stream(query, mode, ...)- Execute streaming RAG queryquery_data(query, mode, ...)- Execute query and return structured data
create_entity(name, description, labels)- Create a new entityupdate_entity(name, description, labels)- Update an existing entitydelete_entity(entity_name)- Delete an entitymerge_entities(source_name, target_name)- Merge two entitiescreate_relation(source, target, relation, description)- Create a relationupdate_relation(source, target, relation, description)- Update a relationdelete_relation(source, target, relation)- Delete a relationget_knowledge_graph(limit)- Get knowledge graph dataget_graph_labels()- Get all graph labelsget_popular_labels(limit)- Get popular labelssearch_labels(q, limit)- Search labelscheck_entity_exists(name)- Check if entity exists
clear_cache()- Clear LLM response cacheget_version()- Get API versionget_tags()- Get available tagsget_running_models()- Get running modelsget_health()- Check API health statusget_auth_status()- Get authentication statuslogin(username, password)- Login and get tokengenerate(**kwargs)- Generate textchat(**kwargs)- Chat with the API
For detailed method signatures and parameters, refer to the source code documentation in src/lightrag/api/_sync_client.py and src/lightrag/api/_async_client.py.
The client supports two authentication methods:
client = SyncLightRagClient(
base_url="https://api.example.com",
api_key="your-api-key"
)The API key is sent in the X-API-Key header.
client = SyncLightRagClient(
base_url="https://api.example.com",
oauth_token="your-oauth-token"
)The OAuth token is sent in the Authorization: Bearer header.
Note:
The library provides two exception types:
LightRagError- Base exception for all LightRAG API errorsLightRagHttpError- Exception for HTTP-related errors
from lightrag.api import SyncLightRagClient, LightRagError, LightRagHttpError
client = SyncLightRagClient(base_url="https://api.example.com", api_key="key")
try:
response = client.query("test query")
except LightRagHttpError as e:
print(f"HTTP error occurred: {e}")
except LightRagError as e:
print(f"LightRAG error occurred: {e}")- π LightRAG Documentation - Official LightRAG project documentation
Why do you write code manually? There is an
openapi-python-clientgenerator.
openapi-python-client generates slop client code.