first commit
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
import ollama
|
||||
from typing import List, Dict, Any
|
||||
import logging
|
||||
|
||||
from app.config import settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class OllamaClient:
|
||||
"""Ollama 客户端封装,仅用于嵌入生成"""
|
||||
|
||||
def __init__(self):
|
||||
self.client = ollama.AsyncClient(host=settings.ollama_base_url)
|
||||
self.model = settings.ollama_embed_model
|
||||
|
||||
async def embed(self, texts: List[str]) -> List[List[float]]:
|
||||
"""批量生成嵌入向量"""
|
||||
if not texts:
|
||||
return []
|
||||
|
||||
try:
|
||||
# Ollama embed 支持批量输入
|
||||
response = await self.client.embed(
|
||||
model=self.model,
|
||||
input=texts
|
||||
)
|
||||
return response["embeddings"]
|
||||
except Exception as e:
|
||||
logger.error(f"Ollama embedding failed: {e}")
|
||||
raise
|
||||
|
||||
async def embed_single(self, text: str) -> List[float]:
|
||||
"""生成单个文本的嵌入向量"""
|
||||
embeddings = await self.embed([text])
|
||||
return embeddings[0] if embeddings else []
|
||||
|
||||
async def health_check(self) -> Dict[str, Any]:
|
||||
"""健康检查"""
|
||||
try:
|
||||
# 尝试列出模型
|
||||
models = await self.client.list()
|
||||
model_names = [m["name"] for m in models.get("models", [])]
|
||||
available = self.model in model_names
|
||||
return {
|
||||
"status": "healthy" if available else "unhealthy",
|
||||
"model": self.model,
|
||||
"available": available,
|
||||
"models": model_names
|
||||
}
|
||||
except Exception as e:
|
||||
return {
|
||||
"status": "unhealthy",
|
||||
"error": str(e)
|
||||
}
|
||||
|
||||
|
||||
# 单例实例
|
||||
ollama_client = OllamaClient()
|
||||
Reference in New Issue
Block a user