Neo4j-LiteLLM——LiteLLM和Neo4j集成解决方案

53 阅读3分钟

最近一段时间在使用Neo4j GraphRAG功能,但注意到现在其不支持非常好用的LLM网关LiteLLM,所以推荐一个非常好用的第三方LLM库,这个库可以让我们在Neo4j GraphRAG中直接使用LiteLLM而不是再去造轮子。

项目详细信息

概述

neo4j_litellm 是一个 Python 包,它通过 LiteLLM 库提供了一个统一的接口,用于将各种大语言模型(LLM)与 Neo4j Graph RAG 框架集成。它支持带有聊天历史和系统指令的同步和异步模型调用。

特性

  • 统一的 LLM 接口:通过 LiteLLM 兼容多个 LLM 提供商
  • Neo4j GraphRAG 集成:实现了来自 neo4j_graphragLLMInterface
  • 同步与异步支持:提供 invoke()ainvoke() 方法
  • 聊天历史支持:通过消息历史记录保持对话上下文
  • 系统指令支持:支持系统提示和指令
  • 灵活配置:可配置提供商、模型、API 端点和密钥

安装

pip install neo4j_litellm

依赖项

  • litellm>=1.77.5 - 统一的 LLM 接口库
  • neo4j_graphrag>=1.9.0 - Neo4j Graph RAG 框架

快速开始

基本用法

from neo4j_litellm import LiteLLMInterface, ChatHistory

# 初始化 LLM 接口
llm = LiteLLMInterface(
    provider="openai",        # LLM 提供商 (例如:openai, anthropic, azure 等)
    model_name="gpt-3.5-turbo",  # 模型名称
    base_url="https://api.openai.com/v1",  # API 基础 URL
    api_key="your-api-key-here"  # API 密钥
)

# 简单调用
response = llm.invoke("Hello, how are you?")
print(response.content)

使用聊天历史

from neo4j_litellm import LiteLLMInterface, ChatHistory
from typing import List

llm = LiteLLMInterface(
    provider="openai",
    model_name="gpt-3.5-turbo",
    base_url="https://api.openai.com/v1",
    api_key="your-api-key-here"
)

# 创建聊天历史
message_history: List[ChatHistory] = [
    {"role": "user", "content": "What's the capital of France?"},
    {"role": "assistant", "content": "The capital of France is Paris."}
]

# 使用聊天历史调用
response = llm.invoke(
    input="Tell me more about Paris",
    message_history=message_history
)
print(response.content)

使用系统指令

llm = LiteLLMInterface(
    provider="openai",
    model_name="gpt-3.5-turbo",
    base_url="https://api.openai.com/v1",
    api_key="your-api-key-here"
)

response = llm.invoke(
    input="Explain quantum computing",
    system_instruction="You are a helpful physics tutor. Provide clear explanations."
)
print(response.content)

异步用法

import asyncio
from neo4j_litellm import LiteLLMInterface

async def main():
    llm = LiteLLMInterface(
        provider="openai",
        model_name="gpt-3.5-turbo",
        base_url="https://api.openai.com/v1",
        api_key="your-api-key-here"
    )
    
    response = await llm.ainvoke("Hello from async!")
    print(response.content)

# 运行异步函数
asyncio.run(main())

API 参考

LiteLLMInterface 类

构造函数
LiteLLMInterface(provider: str, model_name: str, base_url: str, api_key: str)
  • provider:LLM 提供商名称 (例如:"openai"、"anthropic"、"azure" 等)
  • model_name:具体模型名称 (例如:"gpt-3.5-turbo"、"claude-3-sonnet")
  • base_url:API 端点 URL
  • api_key:身份验证 API 密钥
方法

invoke(input: str, message_history: Optional[List[ChatHistory]] = None, system_instruction: Optional[str] = None) -> LLMResponse

同步调用 LLM 的方法。

  • input:用户输入的文本
  • message_history:可选的聊天历史消息列表
  • system_instruction:可选的系统提示
  • 返回:包含 content 字段的 LLMResponse 对象

ainvoke(input: str, message_history: Optional[List[ChatHistory]] = None, system_instruction: Optional[str] = None) -> LLMResponse

异步调用 LLM 的方法。

  • 参数与 invoke() 相同
  • 返回:包含 content 字段的 LLMResponse 对象

ChatHistory 类型

class ChatHistory(TypedDict):
    role: str    # "system"、"assistant" 或 "user"
    content: str # 消息内容

支持的 LLM 提供商

此包支持 LiteLLM 支持的所有 LLM 提供商,包括:

  • OpenAI
  • Anthropic
  • Azure OpenAI
  • Google AI (Gemini)
  • Cohere
  • Hugging Face
  • Dashscope
  • 以及更多...

有关支持的提供商的完整列表,请参阅 LiteLLM 文档

与 Neo4j GraphRAG 集成

此包实现了来自 neo4j_graphragLLMInterface,使其与 Neo4j 的 Graph RAG 框架兼容,用于构建基于知识图谱的检索增强生成应用。以下是如何与 SimpleKGPipeline 知识图谱构建器管道一起使用的示例:

from neo4j import GraphDatabase
from neo4j_graphrag.retrievers import VectorRetriever
from neo4j_litellm import LiteLLMInterface
from neo4j_graphrag.generation import GraphRAG
from neo4j_graphrag.embeddings import OpenAIEmbeddings

# 1. Neo4j 驱动
URI = "neo4j://:7687"
AUTH = ("neo4j", "password")

INDEX_NAME = "index-name"

# 连接到 Neo4j 数据库
driver = GraphDatabase.driver(URI, auth=AUTH)

# 2. 检索器
# 创建 Embedder 对象,用于将用户问题(文本)转换为向量
embedder = OpenAIEmbeddings(model="text-embedding-3-large")

# 初始化检索器
retriever = VectorRetriever(driver, INDEX_NAME, embedder)

# 3. LLM
llm = LiteLLMInterface(
    provider="openai",
    model_name="gpt-3.5-turbo",
    base_url="https://api.openai.com/v1",
    api_key="your-api-key-here"
)

# 初始化 RAG 管道
rag = GraphRAG(retriever=retriever, llm=llm)

# 查询图谱
query_text = "How do I do similarity search in Neo4j?"
response = rag.search(query_text=query_text, retriever_config={"top_k": 5})
print(response.answer)

GitHub库地址

1Vewton/Neo4jGraphRAG-LiteLLMInterface: A LiteLLM LLM component for Neo4j graph RAG.