feat: implement AI legal assistant system MVP
Core modules: - Laws: CRUD, search, AI-powered QA - Analysis: legal research and case management - Contracts: lifecycle management with templates - Signatures: electronic signature workflow Infrastructure: - FastAPI + SQLite + async SQLAlchemy - Docker deployment support - 54 unit tests passing Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
1 parent
830b33c4b3
commit
656f596d7e
51 files changed
+3690
No files matched your search
@@ -0,0 +1 @@
|
||||
# Services package
|
||||
@@ -0,0 +1,134 @@
|
||||
"""Analysis service for legal research."""
|
||||
from typing import List, Optional
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.analysis import LegalAnalysis, Case, AnalysisStatus
|
||||
|
||||
|
||||
class AnalysisService:
|
||||
"""Service for legal analysis operations."""
|
||||
|
||||
def __init__(self, db: AsyncSession):
|
||||
self.db = db
|
||||
|
||||
async def create_analysis(
|
||||
self,
|
||||
user_id: int,
|
||||
title: str,
|
||||
case_description: str,
|
||||
legal_basis: Optional[dict] = None,
|
||||
) -> LegalAnalysis:
|
||||
"""Create a new legal analysis."""
|
||||
analysis = LegalAnalysis(
|
||||
user_id=user_id,
|
||||
title=title,
|
||||
case_description=case_description,
|
||||
legal_basis=legal_basis,
|
||||
)
|
||||
self.db.add(analysis)
|
||||
await self.db.flush()
|
||||
await self.db.refresh(analysis)
|
||||
return analysis
|
||||
|
||||
async def get_analysis_by_id(self, analysis_id: int) -> Optional[LegalAnalysis]:
|
||||
"""Get an analysis by ID."""
|
||||
result = await self.db.execute(
|
||||
select(LegalAnalysis).where(LegalAnalysis.id == analysis_id)
|
||||
)
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
async def get_analyses_by_user(
|
||||
self,
|
||||
user_id: int,
|
||||
skip: int = 0,
|
||||
limit: int = 20,
|
||||
) -> List[LegalAnalysis]:
|
||||
"""Get analyses by user ID."""
|
||||
result = await self.db.execute(
|
||||
select(LegalAnalysis)
|
||||
.where(LegalAnalysis.user_id == user_id)
|
||||
.offset(skip)
|
||||
.limit(limit)
|
||||
.order_by(LegalAnalysis.created_at.desc())
|
||||
)
|
||||
return list(result.scalars().all())
|
||||
|
||||
async def update_analysis(
|
||||
self,
|
||||
analysis_id: int,
|
||||
**kwargs
|
||||
) -> Optional[LegalAnalysis]:
|
||||
"""Update an analysis."""
|
||||
analysis = await self.get_analysis_by_id(analysis_id)
|
||||
if not analysis:
|
||||
return None
|
||||
|
||||
for key, value in kwargs.items():
|
||||
if hasattr(analysis, key) and value is not None:
|
||||
setattr(analysis, key, value)
|
||||
|
||||
await self.db.flush()
|
||||
await self.db.refresh(analysis)
|
||||
return analysis
|
||||
|
||||
async def delete_analysis(self, analysis_id: int) -> bool:
|
||||
"""Delete an analysis."""
|
||||
analysis = await self.get_analysis_by_id(analysis_id)
|
||||
if not analysis:
|
||||
return False
|
||||
|
||||
await self.db.delete(analysis)
|
||||
await self.db.flush()
|
||||
return True
|
||||
|
||||
|
||||
class CaseService:
|
||||
"""Service for case operations."""
|
||||
|
||||
def __init__(self, db: AsyncSession):
|
||||
self.db = db
|
||||
|
||||
async def create_case(
|
||||
self,
|
||||
title: str,
|
||||
case_number: Optional[str] = None,
|
||||
court: Optional[str] = None,
|
||||
case_type: Optional[str] = None,
|
||||
**kwargs
|
||||
) -> Case:
|
||||
"""Create a new case."""
|
||||
case = Case(
|
||||
title=title,
|
||||
case_number=case_number,
|
||||
court=court,
|
||||
case_type=case_type,
|
||||
**kwargs
|
||||
)
|
||||
self.db.add(case)
|
||||
await self.db.flush()
|
||||
await self.db.refresh(case)
|
||||
return case
|
||||
|
||||
async def get_case_by_id(self, case_id: int) -> Optional[Case]:
|
||||
"""Get a case by ID."""
|
||||
result = await self.db.execute(
|
||||
select(Case).where(Case.id == case_id)
|
||||
)
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
async def get_cases_list(
|
||||
self,
|
||||
skip: int = 0,
|
||||
limit: int = 20,
|
||||
case_type: Optional[str] = None,
|
||||
) -> List[Case]:
|
||||
"""Get list of cases."""
|
||||
query = select(Case)
|
||||
|
||||
if case_type:
|
||||
query = query.where(Case.case_type == case_type)
|
||||
|
||||
query = query.offset(skip).limit(limit).order_by(Case.created_at.desc())
|
||||
result = await self.db.execute(query)
|
||||
return list(result.scalars().all())
|
||||
@@ -0,0 +1,171 @@
|
||||
"""Contract service for contract management."""
|
||||
from typing import List, Optional
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.contract import Contract, ContractTemplate, ContractApproval, ContractStatus
|
||||
|
||||
|
||||
class ContractService:
|
||||
"""Service for contract operations."""
|
||||
|
||||
def __init__(self, db: AsyncSession):
|
||||
self.db = db
|
||||
|
||||
async def create_contract(
|
||||
self,
|
||||
title: str,
|
||||
party_a: str,
|
||||
party_b: str,
|
||||
content: str,
|
||||
created_by: int,
|
||||
**kwargs
|
||||
) -> Contract:
|
||||
"""Create a new contract."""
|
||||
contract = Contract(
|
||||
title=title,
|
||||
party_a=party_a,
|
||||
party_b=party_b,
|
||||
content=content,
|
||||
created_by=created_by,
|
||||
**kwargs
|
||||
)
|
||||
self.db.add(contract)
|
||||
await self.db.flush()
|
||||
await self.db.refresh(contract)
|
||||
return contract
|
||||
|
||||
async def get_contract_by_id(self, contract_id: int) -> Optional[Contract]:
|
||||
"""Get a contract by ID."""
|
||||
result = await self.db.execute(
|
||||
select(Contract).where(Contract.id == contract_id)
|
||||
)
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
async def get_contracts_list(
|
||||
self,
|
||||
skip: int = 0,
|
||||
limit: int = 20,
|
||||
status: Optional[ContractStatus] = None,
|
||||
created_by: Optional[int] = None,
|
||||
) -> List[Contract]:
|
||||
"""Get list of contracts."""
|
||||
query = select(Contract)
|
||||
|
||||
if status:
|
||||
query = query.where(Contract.status == status)
|
||||
if created_by:
|
||||
query = query.where(Contract.created_by == created_by)
|
||||
|
||||
query = query.offset(skip).limit(limit).order_by(Contract.created_at.desc())
|
||||
result = await self.db.execute(query)
|
||||
return list(result.scalars().all())
|
||||
|
||||
async def update_contract(
|
||||
self,
|
||||
contract_id: int,
|
||||
**kwargs
|
||||
) -> Optional[Contract]:
|
||||
"""Update a contract."""
|
||||
contract = await self.get_contract_by_id(contract_id)
|
||||
if not contract:
|
||||
return None
|
||||
|
||||
for key, value in kwargs.items():
|
||||
if hasattr(contract, key) and value is not None:
|
||||
setattr(contract, key, value)
|
||||
|
||||
await self.db.flush()
|
||||
await self.db.refresh(contract)
|
||||
return contract
|
||||
|
||||
async def submit_for_approval(self, contract_id: int) -> Optional[Contract]:
|
||||
"""Submit a contract for approval."""
|
||||
return await self.update_contract(
|
||||
contract_id,
|
||||
status=ContractStatus.PENDING_APPROVAL
|
||||
)
|
||||
|
||||
async def approve_contract(
|
||||
self,
|
||||
contract_id: int,
|
||||
approver_id: int,
|
||||
comment: Optional[str] = None,
|
||||
) -> ContractApproval:
|
||||
"""Approve a contract."""
|
||||
approval = ContractApproval(
|
||||
contract_id=contract_id,
|
||||
approver_id=approver_id,
|
||||
status=ContractStatus.APPROVED,
|
||||
comment=comment,
|
||||
)
|
||||
self.db.add(approval)
|
||||
|
||||
# Update contract status
|
||||
await self.update_contract(contract_id, status=ContractStatus.APPROVED)
|
||||
|
||||
await self.db.flush()
|
||||
await self.db.refresh(approval)
|
||||
return approval
|
||||
|
||||
async def reject_contract(
|
||||
self,
|
||||
contract_id: int,
|
||||
approver_id: int,
|
||||
comment: Optional[str] = None,
|
||||
) -> ContractApproval:
|
||||
"""Reject a contract."""
|
||||
approval = ContractApproval(
|
||||
contract_id=contract_id,
|
||||
approver_id=approver_id,
|
||||
status=ContractStatus.REJECTED,
|
||||
comment=comment,
|
||||
)
|
||||
self.db.add(approval)
|
||||
|
||||
# Update contract status
|
||||
await self.update_contract(contract_id, status=ContractStatus.REJECTED)
|
||||
|
||||
await self.db.flush()
|
||||
await self.db.refresh(approval)
|
||||
return approval
|
||||
|
||||
|
||||
class ContractTemplateService:
|
||||
"""Service for contract template operations."""
|
||||
|
||||
def __init__(self, db: AsyncSession):
|
||||
self.db = db
|
||||
|
||||
async def create_template(
|
||||
self,
|
||||
name: str,
|
||||
content: str,
|
||||
created_by: int,
|
||||
contract_type: Optional[str] = None,
|
||||
) -> ContractTemplate:
|
||||
"""Create a contract template."""
|
||||
template = ContractTemplate(
|
||||
name=name,
|
||||
content=content,
|
||||
created_by=created_by,
|
||||
contract_type=contract_type,
|
||||
)
|
||||
self.db.add(template)
|
||||
await self.db.flush()
|
||||
await self.db.refresh(template)
|
||||
return template
|
||||
|
||||
async def get_templates_list(
|
||||
self,
|
||||
skip: int = 0,
|
||||
limit: int = 20,
|
||||
) -> List[ContractTemplate]:
|
||||
"""Get list of templates."""
|
||||
result = await self.db.execute(
|
||||
select(ContractTemplate)
|
||||
.offset(skip)
|
||||
.limit(limit)
|
||||
.order_by(ContractTemplate.created_at.desc())
|
||||
)
|
||||
return list(result.scalars().all())
|
||||
@@ -0,0 +1,137 @@
|
||||
"""Law service for CRUD operations."""
|
||||
from datetime import date
|
||||
from typing import List, Optional
|
||||
from sqlalchemy import select, or_
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.law import Law, LawArticle, LawType, LawStatus
|
||||
|
||||
|
||||
class LawService:
|
||||
"""Service for law CRUD operations."""
|
||||
|
||||
def __init__(self, db: AsyncSession):
|
||||
self.db = db
|
||||
|
||||
async def create_law(
|
||||
self,
|
||||
title: str,
|
||||
law_type: LawType,
|
||||
promulgation_date: date,
|
||||
effective_date: date,
|
||||
issuing_authority: str,
|
||||
content: str,
|
||||
status: LawStatus = LawStatus.EFFECTIVE,
|
||||
document_number: Optional[str] = None,
|
||||
) -> Law:
|
||||
"""Create a new law."""
|
||||
law = Law(
|
||||
title=title,
|
||||
law_type=law_type,
|
||||
promulgation_date=promulgation_date,
|
||||
effective_date=effective_date,
|
||||
status=status,
|
||||
issuing_authority=issuing_authority,
|
||||
content=content,
|
||||
document_number=document_number,
|
||||
)
|
||||
self.db.add(law)
|
||||
await self.db.flush()
|
||||
await self.db.refresh(law)
|
||||
return law
|
||||
|
||||
async def get_law_by_id(self, law_id: int) -> Optional[Law]:
|
||||
"""Get a law by ID."""
|
||||
result = await self.db.execute(
|
||||
select(Law).where(Law.id == law_id)
|
||||
)
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
async def get_laws_list(
|
||||
self,
|
||||
skip: int = 0,
|
||||
limit: int = 20,
|
||||
law_type: Optional[LawType] = None,
|
||||
status: Optional[LawStatus] = None,
|
||||
) -> List[Law]:
|
||||
"""Get list of laws with optional filters."""
|
||||
query = select(Law)
|
||||
|
||||
if law_type:
|
||||
query = query.where(Law.law_type == law_type)
|
||||
if status:
|
||||
query = query.where(Law.status == status)
|
||||
|
||||
query = query.offset(skip).limit(limit).order_by(Law.created_at.desc())
|
||||
result = await self.db.execute(query)
|
||||
return list(result.scalars().all())
|
||||
|
||||
async def update_law(
|
||||
self,
|
||||
law_id: int,
|
||||
**kwargs
|
||||
) -> Optional[Law]:
|
||||
"""Update a law."""
|
||||
law = await self.get_law_by_id(law_id)
|
||||
if not law:
|
||||
return None
|
||||
|
||||
for key, value in kwargs.items():
|
||||
if hasattr(law, key) and value is not None:
|
||||
setattr(law, key, value)
|
||||
|
||||
await self.db.flush()
|
||||
await self.db.refresh(law)
|
||||
return law
|
||||
|
||||
async def delete_law(self, law_id: int) -> bool:
|
||||
"""Delete a law."""
|
||||
law = await self.get_law_by_id(law_id)
|
||||
if not law:
|
||||
return False
|
||||
|
||||
await self.db.delete(law)
|
||||
await self.db.flush()
|
||||
return True
|
||||
|
||||
async def search_laws_by_keyword(
|
||||
self,
|
||||
keyword: str,
|
||||
limit: int = 10
|
||||
) -> List[Law]:
|
||||
"""Search laws by keyword in title or content."""
|
||||
query = select(Law).where(
|
||||
or_(
|
||||
Law.title.contains(keyword),
|
||||
Law.content.contains(keyword),
|
||||
)
|
||||
).limit(limit)
|
||||
|
||||
result = await self.db.execute(query)
|
||||
return list(result.scalars().all())
|
||||
|
||||
async def create_article(
|
||||
self,
|
||||
law_id: int,
|
||||
article_number: str,
|
||||
content: str,
|
||||
) -> LawArticle:
|
||||
"""Create a law article."""
|
||||
article = LawArticle(
|
||||
law_id=law_id,
|
||||
article_number=article_number,
|
||||
content=content,
|
||||
)
|
||||
self.db.add(article)
|
||||
await self.db.flush()
|
||||
await self.db.refresh(article)
|
||||
return article
|
||||
|
||||
async def get_articles_by_law_id(self, law_id: int) -> List[LawArticle]:
|
||||
"""Get articles for a law."""
|
||||
result = await self.db.execute(
|
||||
select(LawArticle)
|
||||
.where(LawArticle.law_id == law_id)
|
||||
.order_by(LawArticle.id)
|
||||
)
|
||||
return list(result.scalars().all())
|
||||
@@ -0,0 +1,123 @@
|
||||
"""LLM service for AI-powered features."""
|
||||
from typing import List, Dict, Any, Optional
|
||||
import httpx
|
||||
|
||||
from app.core.config import settings
|
||||
|
||||
|
||||
class LLMService:
|
||||
"""Service for LLM API interactions."""
|
||||
|
||||
def __init__(self):
|
||||
self.api_base = settings.LLM_API_BASE
|
||||
self.api_key = settings.LLM_API_KEY
|
||||
self.model = settings.LLM_MODEL
|
||||
|
||||
async def chat_completion(
|
||||
self,
|
||||
messages: List[Dict[str, str]],
|
||||
temperature: float = 0.7,
|
||||
max_tokens: int = 2000,
|
||||
) -> str:
|
||||
"""Get chat completion from LLM."""
|
||||
if not self.api_key:
|
||||
# Return mock response for testing
|
||||
return "这是一个模拟的法律回复。"
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.post(
|
||||
f"{self.api_base}/chat/completions",
|
||||
headers={
|
||||
"Authorization": f"Bearer {self.api_key}",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
json={
|
||||
"model": self.model,
|
||||
"messages": messages,
|
||||
"temperature": temperature,
|
||||
"max_tokens": max_tokens,
|
||||
},
|
||||
timeout=60.0,
|
||||
)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
return data["choices"][0]["message"]["content"]
|
||||
|
||||
async def legal_qa(
|
||||
self,
|
||||
question: str,
|
||||
context: Optional[str] = None,
|
||||
) -> str:
|
||||
"""Answer a legal question."""
|
||||
system_prompt = """你是一个专业的法律助手。请根据以下原则回答问题:
|
||||
1. 准确引用相关法律条文
|
||||
2. 解释法律条文的含义和适用条件
|
||||
3. 提供实用的法律建议
|
||||
4. 如不确定,请明确说明"""
|
||||
|
||||
messages = [
|
||||
{"role": "system", "content": system_prompt},
|
||||
]
|
||||
|
||||
if context:
|
||||
messages.append({
|
||||
"role": "user",
|
||||
"content": f"参考以下法律内容:\n{context}\n\n问题:{question}"
|
||||
})
|
||||
else:
|
||||
messages.append({"role": "user", "content": question})
|
||||
|
||||
return await self.chat_completion(messages)
|
||||
|
||||
async def analyze_legal_issue(
|
||||
self,
|
||||
issue_description: str,
|
||||
relevant_laws: Optional[List[str]] = None,
|
||||
) -> str:
|
||||
"""Analyze a legal issue and provide insights."""
|
||||
system_prompt = """你是一个专业的法律分析师。请根据以下结构分析法律问题:
|
||||
1. 问题定性
|
||||
2. 相关法律依据
|
||||
3. 法律分析
|
||||
4. 风险提示
|
||||
5. 建议"""
|
||||
|
||||
user_content = f"请分析以下法律问题:\n{issue_description}"
|
||||
|
||||
if relevant_laws:
|
||||
user_content += f"\n\n相关法律:\n" + "\n".join(relevant_laws)
|
||||
|
||||
messages = [
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": user_content},
|
||||
]
|
||||
|
||||
return await self.chat_completion(messages, temperature=0.5)
|
||||
|
||||
async def review_contract(
|
||||
self,
|
||||
contract_content: str,
|
||||
contract_type: Optional[str] = None,
|
||||
) -> str:
|
||||
"""Review a contract and identify potential issues."""
|
||||
system_prompt = """你是一个专业的合同审查专家。请审查合同并:
|
||||
1. 识别潜在风险条款
|
||||
2. 指出不明确的条款
|
||||
3. 提出修改建议
|
||||
4. 检查法律合规性"""
|
||||
|
||||
user_content = f"请审查以下合同内容:\n{contract_content}"
|
||||
|
||||
if contract_type:
|
||||
user_content = f"合同类型:{contract_type}\n\n{user_content}"
|
||||
|
||||
messages = [
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": user_content},
|
||||
]
|
||||
|
||||
return await self.chat_completion(messages, max_tokens=3000)
|
||||
|
||||
|
||||
# Singleton instance
|
||||
llm_service = LLMService()
|
||||
@@ -0,0 +1,174 @@
|
||||
"""Signature service for electronic signatures."""
|
||||
import hashlib
|
||||
import secrets
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.config import settings
|
||||
from app.models.signature import (
|
||||
SignatureRequest,
|
||||
Signature,
|
||||
SignatureAudit,
|
||||
SignatureStatus,
|
||||
)
|
||||
from app.models.contract import Contract
|
||||
|
||||
|
||||
class SignatureService:
|
||||
"""Service for electronic signature operations."""
|
||||
|
||||
def __init__(self, db: AsyncSession):
|
||||
self.db = db
|
||||
|
||||
def generate_token(self) -> str:
|
||||
"""Generate a secure random token."""
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
def generate_verification_hash(self, content: str) -> str:
|
||||
"""Generate a verification hash for document content."""
|
||||
return hashlib.sha256(content.encode()).hexdigest()
|
||||
|
||||
async def create_signature_request(
|
||||
self,
|
||||
contract_id: int,
|
||||
requester_id: int,
|
||||
signer_name: str,
|
||||
signer_email: str,
|
||||
expire_hours: int = None,
|
||||
) -> SignatureRequest:
|
||||
"""Create a signature request."""
|
||||
expire_hours = expire_hours or settings.SIGNATURE_TOKEN_EXPIRE_HOURS
|
||||
|
||||
request = SignatureRequest(
|
||||
contract_id=contract_id,
|
||||
requester_id=requester_id,
|
||||
signer_name=signer_name,
|
||||
signer_email=signer_email,
|
||||
token=self.generate_token(),
|
||||
expires_at=datetime.utcnow() + timedelta(hours=expire_hours),
|
||||
)
|
||||
self.db.add(request)
|
||||
|
||||
# Create audit log
|
||||
await self.create_audit_log(
|
||||
action="request_created",
|
||||
request_id=request.id,
|
||||
details={"signer_email": signer_email}
|
||||
)
|
||||
|
||||
await self.db.flush()
|
||||
await self.db.refresh(request)
|
||||
return request
|
||||
|
||||
async def get_signature_request_by_token(
|
||||
self,
|
||||
token: str
|
||||
) -> Optional[SignatureRequest]:
|
||||
"""Get a signature request by token."""
|
||||
result = await self.db.execute(
|
||||
select(SignatureRequest).where(SignatureRequest.token == token)
|
||||
)
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
async def get_signature_request_by_id(
|
||||
self,
|
||||
request_id: int
|
||||
) -> Optional[SignatureRequest]:
|
||||
"""Get a signature request by ID."""
|
||||
result = await self.db.execute(
|
||||
select(SignatureRequest).where(SignatureRequest.id == request_id)
|
||||
)
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
async def is_request_valid(self, request: SignatureRequest) -> bool:
|
||||
"""Check if a signature request is valid."""
|
||||
if request.status != SignatureStatus.PENDING:
|
||||
return False
|
||||
if request.expires_at < datetime.utcnow():
|
||||
return False
|
||||
return True
|
||||
|
||||
async def sign_document(
|
||||
self,
|
||||
request: SignatureRequest,
|
||||
signature_data: str,
|
||||
ip_address: Optional[str] = None,
|
||||
user_agent: Optional[str] = None,
|
||||
) -> Signature:
|
||||
"""Sign a document."""
|
||||
# Get contract content for hash
|
||||
result = await self.db.execute(
|
||||
select(Contract).where(Contract.id == request.contract_id)
|
||||
)
|
||||
contract = result.scalar_one_or_none()
|
||||
|
||||
if not contract:
|
||||
raise ValueError("Contract not found")
|
||||
|
||||
verification_hash = self.generate_verification_hash(contract.content)
|
||||
|
||||
signature = Signature(
|
||||
request_id=request.id,
|
||||
signer_name=request.signer_name,
|
||||
signature_data=signature_data,
|
||||
verification_hash=verification_hash,
|
||||
ip_address=ip_address,
|
||||
user_agent=user_agent,
|
||||
)
|
||||
self.db.add(signature)
|
||||
|
||||
# Update request status
|
||||
request.status = SignatureStatus.SIGNED
|
||||
|
||||
# Create audit log
|
||||
await self.create_audit_log(
|
||||
action="document_signed",
|
||||
signature_id=signature.id,
|
||||
request_id=request.id,
|
||||
ip_address=ip_address
|
||||
)
|
||||
|
||||
await self.db.flush()
|
||||
await self.db.refresh(signature)
|
||||
return signature
|
||||
|
||||
async def verify_signature(
|
||||
self,
|
||||
signature_id: int,
|
||||
content: str
|
||||
) -> bool:
|
||||
"""Verify a signature against document content."""
|
||||
result = await self.db.execute(
|
||||
select(Signature).where(Signature.id == signature_id)
|
||||
)
|
||||
signature = result.scalar_one_or_none()
|
||||
|
||||
if not signature:
|
||||
return False
|
||||
|
||||
current_hash = self.generate_verification_hash(content)
|
||||
return current_hash == signature.verification_hash
|
||||
|
||||
async def create_audit_log(
|
||||
self,
|
||||
action: str,
|
||||
signature_id: Optional[int] = None,
|
||||
request_id: Optional[int] = None,
|
||||
details: Optional[dict] = None,
|
||||
ip_address: Optional[str] = None,
|
||||
) -> SignatureAudit:
|
||||
"""Create an audit log entry."""
|
||||
audit = SignatureAudit(
|
||||
action=action,
|
||||
signature_id=signature_id,
|
||||
request_id=request_id,
|
||||
details=details,
|
||||
ip_address=ip_address,
|
||||
)
|
||||
self.db.add(audit)
|
||||
await self.db.flush()
|
||||
await self.db.refresh(audit)
|
||||
return audit
|
||||
@@ -0,0 +1,107 @@
|
||||
"""Vector service for embedding and similarity search."""
|
||||
import numpy as np
|
||||
from typing import List, Dict, Any, Optional
|
||||
import httpx
|
||||
|
||||
from app.core.config import settings
|
||||
|
||||
|
||||
class VectorService:
|
||||
"""Service for vector embeddings and similarity search."""
|
||||
|
||||
def __init__(self):
|
||||
self.api_base = settings.EMBEDDING_API_BASE
|
||||
self.api_key = settings.EMBEDDING_API_KEY or settings.LLM_API_KEY
|
||||
self.model = settings.EMBEDDING_MODEL
|
||||
self.dimension = settings.EMBEDDING_DIMENSION
|
||||
|
||||
async def get_embedding(self, text: str) -> List[float]:
|
||||
"""Get embedding for a text using external API."""
|
||||
if not self.api_key:
|
||||
# Return mock embedding for testing
|
||||
return [0.0] * self.dimension
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.post(
|
||||
f"{self.api_base}/embeddings",
|
||||
headers={
|
||||
"Authorization": f"Bearer {self.api_key}",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
json={
|
||||
"model": self.model,
|
||||
"input": text,
|
||||
},
|
||||
timeout=30.0,
|
||||
)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
return data["data"][0]["embedding"]
|
||||
|
||||
async def get_embeddings(self, texts: List[str]) -> List[List[float]]:
|
||||
"""Get embeddings for multiple texts."""
|
||||
if not self.api_key:
|
||||
return [[0.0] * self.dimension for _ in texts]
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.post(
|
||||
f"{self.api_base}/embeddings",
|
||||
headers={
|
||||
"Authorization": f"Bearer {self.api_key}",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
json={
|
||||
"model": self.model,
|
||||
"input": texts,
|
||||
},
|
||||
timeout=60.0,
|
||||
)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
return [item["embedding"] for item in data["data"]]
|
||||
|
||||
def cosine_similarity(
|
||||
self,
|
||||
vec1: List[float],
|
||||
vec2: List[float]
|
||||
) -> float:
|
||||
"""Calculate cosine similarity between two vectors."""
|
||||
arr1 = np.array(vec1)
|
||||
arr2 = np.array(vec2)
|
||||
|
||||
dot_product = np.dot(arr1, arr2)
|
||||
norm1 = np.linalg.norm(arr1)
|
||||
norm2 = np.linalg.norm(arr2)
|
||||
|
||||
if norm1 == 0 or norm2 == 0:
|
||||
return 0.0
|
||||
|
||||
return float(dot_product / (norm1 * norm2))
|
||||
|
||||
def search_similar(
|
||||
self,
|
||||
query_embedding: List[float],
|
||||
stored_vectors: List[Dict[str, Any]],
|
||||
top_k: int = 5
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""Search for similar vectors."""
|
||||
results = []
|
||||
|
||||
for item in stored_vectors:
|
||||
similarity = self.cosine_similarity(
|
||||
query_embedding,
|
||||
item["embedding"]
|
||||
)
|
||||
results.append({
|
||||
"id": item["id"],
|
||||
"similarity": similarity,
|
||||
})
|
||||
|
||||
# Sort by similarity descending
|
||||
results.sort(key=lambda x: x["similarity"], reverse=True)
|
||||
|
||||
return results[:top_k]
|
||||
|
||||
|
||||
# Singleton instance
|
||||
vector_service = VectorService()
|
||||
Reference in new issue
Block a user