ai相关: llamaindex: 把数据写入到milvus

一,安装用到的第三方库

$ pip install llama-index-vector-stores-milvus

二,启动milvus服务

$ systemctl status milvus.service 
○ milvus.service - Milvus Standalone Server
     Loaded: loaded (/usr/lib/systemd/system/milvus.service; disabled; preset: enabled)
     Active: inactive (dead)
$ systemctl start milvus.service 
$ systemctl status milvus.service 
● milvus.service - Milvus Standalone Server
     Loaded: loaded (/usr/lib/systemd/system/milvus.service; disabled; preset: enabled)
     Active: active (running) since Sat 2026-08-08 15:51:57 CST; 4s ago
   Main PID: 6220 (milvus)
      Tasks: 18 (limit: 19029)
     Memory: 307.5M (peak: 322.5M)
        CPU: 1.588s
     CGroup: /system.slice/milvus.service
             ├─6220 /usr/bin/milvus run standalone
             └─6267 /usr/bin/dbus-daemon --syslog --fork --print-pid 5 --print-address 8 --session

8月 08 15:52:01 liuhongdi-pc milvus[6220]: [2026/08/08 15:52:01.852 +08:00] [INFO] [observers/collection_observer.go:417] ["collection load status updated"] [collectionID>

三,代码

import os
import uuid
from fastapi import FastAPI, Body, HTTPException, Form

from llama_index.llms.dashscope import DashScope
from llama_index.embeddings.dashscope import DashScopeEmbedding
from llama_index.core.memory import ChatMemoryBuffer
from llama_index.storage.chat_store.redis import RedisChatStore

from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, StorageContext, Settings
from llama_index.embeddings.dashscope import DashScopeEmbedding
from llama_index.vector_stores.milvus import MilvusVectorStore


app = FastAPI(title="AI 智能客服系统")


# ==================== 1. 配置阿里通义千问模型 ====================
# !!!请在环境变量中设置 DASHSCOPE_API_KEY,或在此处直接硬编码赋值!!!
DASHSCOPE_API_KEY = os.environ.get("DASHSCOPE_API_KEY", "YOUR_DASHSCOPE_API_KEY")
# 全局配置大语言模型 (推荐使用适合复杂业务的 qwen-plus)
Settings.llm = DashScope(
    model_name="qwen-plus",
    api_key=DASHSCOPE_API_KEY,
    temperature=0.1  # 调低随机性,使其严格根据知识库回答
)

# 全局配置向量化模型 (推荐中文性能强大的 v3 版本)
Settings.embed_model = DashScopeEmbedding(
    model_name="text-embedding-v3",
    api_key=DASHSCOPE_API_KEY
)

# 第一步:把数据写入到milvus

# 1. 初始化 Milvus 向量存储
vector_store = MilvusVectorStore(
    uri="http://localhost:19530",   # Milvus 服务地址(若使用本地轻量版,可写为 "./milvus_demo.db")
    collection_name="ai_service_docs", # 指定 Collection 名字
    dim=1024,                       # 向量维度(需与使用的 Embedding 模型维度一致)
    overwrite=True                 # 是否覆盖已存在的 collection
)

# 2. 创建 StorageContext
storage_context = StorageContext.from_defaults(vector_store=vector_store)

# 3. 读取本地文档并生成索引(此步骤会自动将 Embedding 写入 Milvus)
documents = SimpleDirectoryReader("./data").load_data()
index = VectorStoreIndex.from_documents(
    documents,
    storage_context=storage_context
)


# ==================== 2. 全局知识库与 Redis 初始化 ====================

# 2. 从向量存储直接重建 Index 对象(不会重复写入数据)
global_index = VectorStoreIndex.from_vector_store(vector_store=vector_store)

# 配置 Redis 存储多会话聊天记录(假设 Redis 运行在本地默认端口)
try:
    chat_store = RedisChatStore(redis_url="redis://localhost:6379")
except Exception:
    print("警告: 无法链接 Redis,本 Demo 将降级使用内存存储。生产环境请务必开启 Redis!")
    chat_store = None

# ==================== 3. 智能客服聊天接口 ====================
@app.post("/api/chat")
async def chat_endpoint(
        session_id: str = Form(default=None),
        message: str = Form(..., description="用户输入的聊天内容")
):
    # 如果是新会话,前端没有传 session_id,则后端自动生成一个 UUID
    if not session_id:
        session_id = str(uuid.uuid4())

    # 配置当前会话的历史记忆缓冲区
    if chat_store:
        memory = ChatMemoryBuffer.from_defaults(
            token_limit=3000,  # 限制记忆总长度,防止超出大模型窗口
            chat_store=chat_store,
            chat_store_key=f"user_session:{session_id}"  # 在 Redis 中作为 Key 隔离用户
        )
    else:
        # Redis 未启动时的内存降级备用方案
        memory = ChatMemoryBuffer.from_defaults(token_limit=3000)

    # 创建基于 RAG 的聊天引擎
    chat_engine = global_index.as_chat_engine(
        chat_mode="condense_plus_context",  # 最适合多轮 RAG 客服的模式
        memory=memory,
        context_prompt=(
            "你是一个专业的企业线上智能客服。请严格根据以下参考资料回答用户的问题。\n"
            "如果你在资料中找不到答案,请礼貌地回复:'抱歉,我暂时无法回答这个问题,正在为您转接人工客服...'\n"
            "参考资料如下:\n"
            "---------------------\n"
            "{context_str}\n"
            "---------------------\n"
        )
    )

    try:
        # 执行多轮对话检索与生成
        response = chat_engine.chat(message)

        return {
            "session_id": session_id,
            "response": str(response)
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"调用模型失败: {str(e)}")

 

 

posted @ 2026-08-08 16:31  刘宏缔的架构森林  阅读(5)  评论(0)    收藏  举报