use langchainrust::retrieval::graph_rag::{GraphRAG, GraphRAGConfig, QueryMode};
use langchainrust::{Document, OpenAIChat, OpenAIConfig};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let api_key = std::env::var("OPENAI_API_KEY")
.expect("please set the OPENAI_API_KEY environment variable");
let base_url = std::env::var("OPENAI_BASE_URL")
.unwrap_or_else(|_| "https://api.openai.com/v1".to_string());
let llm = OpenAIChat::new(OpenAIConfig {
api_key,
base_url,
model: "gpt-4o-mini".to_string(),
..Default::default()
});
let graph_rag = GraphRAG::new(llm).with_config(
GraphRAGConfig::new()
.with_max_entities_per_doc(10)
.with_max_relations_per_doc(10),
);
let docs = vec![
Document::new("Alice is a professor at Tsinghua University, specializing in artificial intelligence."),
Document::new("Bob is Alice's student, currently researching large language models."),
Document::new("Charlie is also Alice's student, researching computer vision."),
];
graph_rag.add_documents(&docs).await?;
println!("Documents added, entities and relations extracted");
graph_rag.build_communities().await?;
println!("Community detection finished");
let local_result = graph_rag
.query("Who are Alice's students?", QueryMode::Local)
.await?;
println!("\n[Local query] Who are Alice's students?");
println!("Answer: {}", local_result.answer);
let global_result = graph_rag
.query("What research areas does this knowledge base cover?", QueryMode::Global)
.await?;
println!("\n[Global query] Which research areas are covered?");
println!("Answer: {}", global_result.answer);
let hybrid_result = graph_rag
.query("What is Alice's research group working on?", QueryMode::Hybrid)
.await?;
println!("\n[Hybrid query] What is Alice's research group working on?");
println!("Answer: {}", hybrid_result.answer);
Ok(())
}