mirror of https://github.com/kortix-ai/suna.git
wip
This commit is contained in:
parent
5d2eb11019
commit
e38d8f327e
|
@ -0,0 +1 @@
|
|||
# Admin module for administrative API endpoints
|
|
@ -0,0 +1,42 @@
|
|||
from fastapi import APIRouter, HTTPException, Depends
|
||||
from typing import Optional
|
||||
from utils.auth_utils import verify_admin_api_key
|
||||
from utils.suna_default_agent_service import SunaDefaultAgentService
|
||||
from utils.logger import logger
|
||||
|
||||
router = APIRouter(prefix="/admin", tags=["admin"])
|
||||
|
||||
@router.post("/suna-agents/install-user/{account_id}")
|
||||
async def admin_install_suna_for_user(
|
||||
account_id: str,
|
||||
replace_existing: bool = False,
|
||||
_: bool = Depends(verify_admin_api_key)
|
||||
):
|
||||
"""Install Suna agent for a specific user account.
|
||||
|
||||
Args:
|
||||
account_id: The account ID to install Suna agent for
|
||||
replace_existing: Whether to replace existing Suna agent if found
|
||||
|
||||
Returns:
|
||||
Success message with agent_id if successful
|
||||
|
||||
Raises:
|
||||
HTTPException: If installation fails
|
||||
"""
|
||||
logger.info(f"Admin installing Suna agent for user: {account_id}")
|
||||
|
||||
service = SunaDefaultAgentService()
|
||||
agent_id = await service.install_suna_agent_for_user(account_id, replace_existing)
|
||||
|
||||
if agent_id:
|
||||
return {
|
||||
"success": True,
|
||||
"message": f"Successfully installed Suna agent for user {account_id}",
|
||||
"agent_id": agent_id
|
||||
}
|
||||
else:
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail=f"Failed to install Suna agent for user {account_id}"
|
||||
)
|
|
@ -28,7 +28,7 @@ from .config_helper import extract_agent_config, build_unified_config, extract_t
|
|||
from .versioning.facade import version_manager
|
||||
from .versioning.api.routes import router as version_router
|
||||
from .versioning.infrastructure.dependencies import set_db_connection
|
||||
from agent.services.suna_default_agent_service import SunaDefaultAgentService
|
||||
from utils.suna_default_agent_service import SunaDefaultAgentService
|
||||
|
||||
router = APIRouter()
|
||||
router.include_router(version_router)
|
||||
|
@ -243,8 +243,6 @@ async def stop_agent_run(agent_run_id: str, error_message: Optional[str] = None)
|
|||
|
||||
logger.info(f"Successfully initiated stop process for agent run: {agent_run_id}")
|
||||
|
||||
|
||||
|
||||
async def get_agent_run_with_access_check(client, agent_run_id: str, user_id: str):
|
||||
agent_run = await client.table('agent_runs').select('*').eq('id', agent_run_id).execute()
|
||||
if not agent_run.data:
|
||||
|
@ -256,8 +254,6 @@ async def get_agent_run_with_access_check(client, agent_run_id: str, user_id: st
|
|||
return agent_run_data
|
||||
|
||||
|
||||
|
||||
|
||||
@router.post("/thread/{thread_id}/agent/start")
|
||||
async def start_agent(
|
||||
thread_id: str,
|
||||
|
@ -2517,26 +2513,5 @@ async def get_agent_tools(
|
|||
mcp_tools.append({"name": tool_name, "server": server, "enabled": True})
|
||||
return {"agentpress_tools": agentpress_tools, "mcp_tools": mcp_tools}
|
||||
|
||||
@router.post("/admin/suna-agents/install-user/{account_id}")
|
||||
async def admin_install_suna_for_user(
|
||||
account_id: str,
|
||||
replace_existing: bool = False,
|
||||
_: bool = Depends(verify_admin_api_key)
|
||||
):
|
||||
logger.info(f"Admin installing Suna agent for user: {account_id}")
|
||||
|
||||
service = SunaDefaultAgentService()
|
||||
agent_id = await service.install_suna_agent_for_user(account_id, replace_existing)
|
||||
|
||||
if agent_id:
|
||||
return {
|
||||
"success": True,
|
||||
"message": f"Successfully installed Suna agent for user {account_id}",
|
||||
"agent_id": agent_id
|
||||
}
|
||||
else:
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail=f"Failed to install Suna agent for user {account_id}"
|
||||
)
|
||||
|
||||
|
||||
|
|
|
@ -34,8 +34,6 @@ from agentpress.tool import SchemaType
|
|||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
|
||||
async def run_agent(
|
||||
thread_id: str,
|
||||
project_id: str,
|
||||
|
|
|
@ -1 +0,0 @@
|
|||
# Agent services initialization
|
|
@ -192,6 +192,9 @@ api_router.include_router(pipedream_api.router)
|
|||
from local_env_manager import api as local_env_manager_api
|
||||
api_router.include_router(local_env_manager_api.router)
|
||||
|
||||
from admin import api as admin_api
|
||||
api_router.include_router(admin_api.router)
|
||||
|
||||
@api_router.get("/health")
|
||||
async def health_check():
|
||||
logger.info("Health check endpoint called")
|
||||
|
|
|
@ -1 +0,0 @@
|
|||
# Auth Module
|
|
@ -2,7 +2,7 @@ import json
|
|||
from typing import List, Optional
|
||||
from fastapi import APIRouter, HTTPException, Depends, UploadFile, File, Form, BackgroundTasks
|
||||
from pydantic import BaseModel, Field, HttpUrl
|
||||
from utils.auth_utils import get_current_user_id_from_jwt
|
||||
from utils.auth_utils import get_current_user_id_from_jwt, verify_agent_access
|
||||
from services.supabase import DBConnection
|
||||
from knowledge_base.file_processor import FileProcessor
|
||||
from utils.logger import logger
|
||||
|
@ -51,12 +51,6 @@ class UpdateKnowledgeBaseEntryRequest(BaseModel):
|
|||
usage_context: Optional[str] = Field(None, pattern="^(always|on_request|contextual)$")
|
||||
is_active: Optional[bool] = None
|
||||
|
||||
class GitRepositoryRequest(BaseModel):
|
||||
git_url: HttpUrl
|
||||
branch: str = "main"
|
||||
include_patterns: Optional[List[str]] = None
|
||||
exclude_patterns: Optional[List[str]] = None
|
||||
|
||||
class ProcessingJobResponse(BaseModel):
|
||||
job_id: str
|
||||
job_type: str
|
||||
|
@ -71,61 +65,6 @@ class ProcessingJobResponse(BaseModel):
|
|||
|
||||
db = DBConnection()
|
||||
|
||||
@router.get("/threads/{thread_id}", response_model=KnowledgeBaseListResponse)
|
||||
async def get_thread_knowledge_base(
|
||||
thread_id: str,
|
||||
include_inactive: bool = False,
|
||||
user_id: str = Depends(get_current_user_id_from_jwt)
|
||||
):
|
||||
if not await is_enabled("knowledge_base"):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="This feature is not available at the moment."
|
||||
)
|
||||
|
||||
"""Get all knowledge base entries for a thread"""
|
||||
try:
|
||||
client = await db.client
|
||||
|
||||
thread_result = await client.table('threads').select('*').eq('thread_id', thread_id).execute()
|
||||
if not thread_result.data:
|
||||
raise HTTPException(status_code=404, detail="Thread not found")
|
||||
|
||||
result = await client.rpc('get_thread_knowledge_base', {
|
||||
'p_thread_id': thread_id,
|
||||
'p_include_inactive': include_inactive
|
||||
}).execute()
|
||||
|
||||
entries = []
|
||||
total_tokens = 0
|
||||
|
||||
for entry_data in result.data or []:
|
||||
entry = KnowledgeBaseEntryResponse(
|
||||
entry_id=entry_data['entry_id'],
|
||||
name=entry_data['name'],
|
||||
description=entry_data['description'],
|
||||
content=entry_data['content'],
|
||||
usage_context=entry_data['usage_context'],
|
||||
is_active=entry_data['is_active'],
|
||||
content_tokens=entry_data.get('content_tokens'),
|
||||
created_at=entry_data['created_at'],
|
||||
updated_at=entry_data.get('updated_at', entry_data['created_at'])
|
||||
)
|
||||
entries.append(entry)
|
||||
total_tokens += entry_data.get('content_tokens', 0) or 0
|
||||
|
||||
return KnowledgeBaseListResponse(
|
||||
entries=entries,
|
||||
total_count=len(entries),
|
||||
total_tokens=total_tokens
|
||||
)
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting knowledge base for thread {thread_id}: {str(e)}")
|
||||
raise HTTPException(status_code=500, detail="Failed to retrieve knowledge base")
|
||||
|
||||
|
||||
@router.get("/agents/{agent_id}", response_model=KnowledgeBaseListResponse)
|
||||
async def get_agent_knowledge_base(
|
||||
|
@ -143,9 +82,8 @@ async def get_agent_knowledge_base(
|
|||
try:
|
||||
client = await db.client
|
||||
|
||||
agent_result = await client.table('agents').select('*').eq('agent_id', agent_id).eq('account_id', user_id).execute()
|
||||
if not agent_result.data:
|
||||
raise HTTPException(status_code=404, detail="Agent not found or access denied")
|
||||
# Verify agent access
|
||||
await verify_agent_access(client, agent_id, user_id)
|
||||
|
||||
result = await client.rpc('get_agent_knowledge_base', {
|
||||
'p_agent_id': agent_id,
|
||||
|
@ -202,11 +140,9 @@ async def create_agent_knowledge_base_entry(
|
|||
try:
|
||||
client = await db.client
|
||||
|
||||
agent_result = await client.table('agents').select('account_id').eq('agent_id', agent_id).eq('account_id', user_id).execute()
|
||||
if not agent_result.data:
|
||||
raise HTTPException(status_code=404, detail="Agent not found or access denied")
|
||||
|
||||
account_id = agent_result.data[0]['account_id']
|
||||
# Verify agent access and get agent data
|
||||
agent_data = await verify_agent_access(client, agent_id, user_id)
|
||||
account_id = agent_data['account_id']
|
||||
|
||||
insert_data = {
|
||||
'agent_id': agent_id,
|
||||
|
@ -259,11 +195,9 @@ async def upload_file_to_agent_kb(
|
|||
try:
|
||||
client = await db.client
|
||||
|
||||
agent_result = await client.table('agents').select('account_id').eq('agent_id', agent_id).eq('account_id', user_id).execute()
|
||||
if not agent_result.data:
|
||||
raise HTTPException(status_code=404, detail="Agent not found or access denied")
|
||||
|
||||
account_id = agent_result.data[0]['account_id']
|
||||
# Verify agent access and get agent data
|
||||
agent_data = await verify_agent_access(client, agent_id, user_id)
|
||||
account_id = agent_data['account_id']
|
||||
|
||||
file_content = await file.read()
|
||||
job_id = await client.rpc('create_agent_kb_processing_job', {
|
||||
|
@ -320,9 +254,8 @@ async def get_agent_processing_jobs(
|
|||
try:
|
||||
client = await db.client
|
||||
|
||||
agent_result = await client.table('agents').select('account_id').eq('agent_id', agent_id).eq('account_id', user_id).execute()
|
||||
if not agent_result.data:
|
||||
raise HTTPException(status_code=404, detail="Agent not found or access denied")
|
||||
# Verify agent access
|
||||
await verify_agent_access(client, agent_id, user_id)
|
||||
|
||||
result = await client.rpc('get_agent_kb_processing_jobs', {
|
||||
'p_agent_id': agent_id,
|
||||
|
@ -418,9 +351,8 @@ async def get_agent_knowledge_base_context(
|
|||
try:
|
||||
client = await db.client
|
||||
|
||||
agent_result = await client.table('agents').select('agent_id').eq('agent_id', agent_id).eq('account_id', user_id).execute()
|
||||
if not agent_result.data:
|
||||
raise HTTPException(status_code=404, detail="Agent not found or access denied")
|
||||
# Verify agent access
|
||||
await verify_agent_access(client, agent_id, user_id)
|
||||
|
||||
result = await client.rpc('get_agent_knowledge_base_context', {
|
||||
'p_agent_id': agent_id,
|
||||
|
@ -441,82 +373,3 @@ async def get_agent_knowledge_base_context(
|
|||
logger.error(f"Error getting knowledge base context for agent {agent_id}: {str(e)}")
|
||||
raise HTTPException(status_code=500, detail="Failed to retrieve agent knowledge base context")
|
||||
|
||||
|
||||
@router.get("/threads/{thread_id}/context")
|
||||
async def get_knowledge_base_context(
|
||||
thread_id: str,
|
||||
max_tokens: int = 4000,
|
||||
user_id: str = Depends(get_current_user_id_from_jwt)
|
||||
):
|
||||
if not await is_enabled("knowledge_base"):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="This feature is not available at the moment."
|
||||
)
|
||||
|
||||
"""Get knowledge base context for agent prompts"""
|
||||
try:
|
||||
client = await db.client
|
||||
thread_result = await client.table('threads').select('thread_id').eq('thread_id', thread_id).execute()
|
||||
if not thread_result.data:
|
||||
raise HTTPException(status_code=404, detail="Thread not found")
|
||||
|
||||
result = await client.rpc('get_knowledge_base_context', {
|
||||
'p_thread_id': thread_id,
|
||||
'p_max_tokens': max_tokens
|
||||
}).execute()
|
||||
|
||||
context = result.data if result.data else None
|
||||
|
||||
return {
|
||||
"context": context,
|
||||
"max_tokens": max_tokens,
|
||||
"thread_id": thread_id
|
||||
}
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting knowledge base context for thread {thread_id}: {str(e)}")
|
||||
raise HTTPException(status_code=500, detail="Failed to retrieve knowledge base context")
|
||||
|
||||
@router.get("/threads/{thread_id}/combined-context")
|
||||
async def get_combined_knowledge_base_context(
|
||||
thread_id: str,
|
||||
agent_id: Optional[str] = None,
|
||||
max_tokens: int = 4000,
|
||||
user_id: str = Depends(get_current_user_id_from_jwt)
|
||||
):
|
||||
if not await is_enabled("knowledge_base"):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="This feature is not available at the moment."
|
||||
)
|
||||
|
||||
"""Get combined knowledge base context from both thread and agent sources"""
|
||||
try:
|
||||
client = await db.client
|
||||
thread_result = await client.table('threads').select('thread_id').eq('thread_id', thread_id).execute()
|
||||
if not thread_result.data:
|
||||
raise HTTPException(status_code=404, detail="Thread not found")
|
||||
|
||||
result = await client.rpc('get_combined_knowledge_base_context', {
|
||||
'p_thread_id': thread_id,
|
||||
'p_agent_id': agent_id,
|
||||
'p_max_tokens': max_tokens
|
||||
}).execute()
|
||||
|
||||
context = result.data if result.data else None
|
||||
|
||||
return {
|
||||
"context": context,
|
||||
"max_tokens": max_tokens,
|
||||
"thread_id": thread_id,
|
||||
"agent_id": agent_id
|
||||
}
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting combined knowledge base context for thread {thread_id}: {str(e)}")
|
||||
raise HTTPException(status_code=500, detail="Failed to retrieve combined knowledge base context")
|
|
@ -33,7 +33,7 @@ from pathlib import Path
|
|||
backend_dir = Path(__file__).parent.parent
|
||||
sys.path.insert(0, str(backend_dir))
|
||||
|
||||
from agent.services.suna_default_agent_service import SunaDefaultAgentService
|
||||
from utils.suna_default_agent_service import SunaDefaultAgentService
|
||||
from services.supabase import DBConnection
|
||||
from utils.logger import logger
|
||||
|
||||
|
|
|
@ -267,7 +267,7 @@ async def get_optional_user_id(request: Request) -> Optional[str]:
|
|||
return None
|
||||
|
||||
async def verify_admin_api_key(x_admin_api_key: Optional[str] = Header(None)):
|
||||
if not config.ADMIN_API_KEY:
|
||||
if not config.KORTIX_ADMIN_API_KEY:
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="Admin API key not configured on server"
|
||||
|
@ -279,10 +279,39 @@ async def verify_admin_api_key(x_admin_api_key: Optional[str] = Header(None)):
|
|||
detail="Admin API key required. Include X-Admin-Api-Key header."
|
||||
)
|
||||
|
||||
if x_admin_api_key != config.ADMIN_API_KEY:
|
||||
if x_admin_api_key != config.KORTIX_ADMIN_API_KEY:
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Invalid admin API key"
|
||||
)
|
||||
|
||||
return True
|
||||
|
||||
async def verify_agent_access(client, agent_id: str, user_id: str) -> dict:
|
||||
"""
|
||||
Verify that a user has access to a specific agent based on ownership.
|
||||
|
||||
Args:
|
||||
client: The Supabase client
|
||||
agent_id: The agent ID to check access for
|
||||
user_id: The user ID to check permissions for
|
||||
|
||||
Returns:
|
||||
dict: Agent data if access is granted
|
||||
|
||||
Raises:
|
||||
HTTPException: If the user doesn't have access to the agent or agent doesn't exist
|
||||
"""
|
||||
try:
|
||||
agent_result = await client.table('agents').select('*').eq('agent_id', agent_id).eq('account_id', user_id).execute()
|
||||
|
||||
if not agent_result.data:
|
||||
raise HTTPException(status_code=404, detail="Agent not found or access denied")
|
||||
|
||||
return agent_result.data[0]
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
structlog.error(f"Error verifying agent access for agent {agent_id}, user {user_id}: {str(e)}")
|
||||
raise HTTPException(status_code=500, detail="Failed to verify agent access")
|
||||
|
|
|
@ -232,7 +232,7 @@ class Configuration:
|
|||
LANGFUSE_HOST: str = "https://cloud.langfuse.com"
|
||||
|
||||
# Admin API key for server-side operations
|
||||
ADMIN_API_KEY: Optional[str] = None
|
||||
KORTIX_ADMIN_API_KEY: Optional[str] = None
|
||||
|
||||
@property
|
||||
def STRIPE_PRODUCT_ID(self) -> str:
|
||||
|
|
|
@ -5,5 +5,6 @@ NEXT_PUBLIC_BACKEND_URL="http://localhost:8000/api"
|
|||
NEXT_PUBLIC_URL="http://localhost:3000"
|
||||
NEXT_PUBLIC_GOOGLE_CLIENT_ID=""
|
||||
OPENAI_API_KEY=""
|
||||
KORTIX_ADMIN_API_KEY=""
|
||||
|
||||
EDGE_CONFIG="https://edge-config.vercel.com/REDACTED?token=REDACTED"
|
||||
|
|
|
@ -6,10 +6,10 @@ import { redirect } from 'next/navigation';
|
|||
async function sendWelcomeEmail(email: string, name?: string) {
|
||||
try {
|
||||
const backendUrl = process.env.NEXT_PUBLIC_BACKEND_URL;
|
||||
const adminApiKey = process.env.ADMIN_API_KEY;
|
||||
const adminApiKey = process.env.KORTIX_ADMIN_API_KEY;
|
||||
|
||||
if (!adminApiKey) {
|
||||
console.error('ADMIN_API_KEY not configured');
|
||||
console.error('KORTIX_ADMIN_API_KEY not configured');
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
|
@ -1,520 +0,0 @@
|
|||
'use client';
|
||||
|
||||
import React, { useState } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import {
|
||||
Plus,
|
||||
Edit2,
|
||||
Trash2,
|
||||
Clock,
|
||||
MoreVertical,
|
||||
AlertCircle,
|
||||
FileText,
|
||||
Eye,
|
||||
EyeOff,
|
||||
Globe,
|
||||
Search,
|
||||
Loader2,
|
||||
} from 'lucide-react';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import {
|
||||
useKnowledgeBaseEntries,
|
||||
useCreateKnowledgeBaseEntry,
|
||||
useUpdateKnowledgeBaseEntry,
|
||||
useDeleteKnowledgeBaseEntry,
|
||||
} from '@/hooks/react-query/knowledge-base/use-knowledge-base-queries';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { CreateKnowledgeBaseEntryRequest, KnowledgeBaseEntry, UpdateKnowledgeBaseEntryRequest } from '@/hooks/react-query/knowledge-base/types';
|
||||
|
||||
interface KnowledgeBaseManagerProps {
|
||||
threadId: string;
|
||||
}
|
||||
|
||||
interface EditDialogData {
|
||||
entry?: KnowledgeBaseEntry;
|
||||
isOpen: boolean;
|
||||
}
|
||||
|
||||
const USAGE_CONTEXT_OPTIONS = [
|
||||
{
|
||||
value: 'always',
|
||||
label: 'Always Active',
|
||||
icon: Globe,
|
||||
color: 'bg-green-50 text-green-700 border-green-200 dark:bg-green-900/20 dark:text-green-400 dark:border-green-800'
|
||||
},
|
||||
// {
|
||||
// value: 'contextual',
|
||||
// label: 'Smart Context',
|
||||
// description: 'Included when contextually relevant',
|
||||
// icon: Target,
|
||||
// color: 'bg-blue-50 text-blue-700 border-blue-200 dark:bg-blue-900/20 dark:text-blue-400 dark:border-blue-800'
|
||||
// },
|
||||
// {
|
||||
// value: 'on_request',
|
||||
// label: 'On Demand',
|
||||
// description: 'Only when explicitly requested',
|
||||
// icon: Zap,
|
||||
// color: 'bg-amber-50 text-amber-700 border-amber-200 dark:bg-amber-900/20 dark:text-amber-400 dark:border-amber-800'
|
||||
// },
|
||||
] as const;
|
||||
|
||||
const KnowledgeBaseSkeleton = () => (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="relative w-full">
|
||||
<Skeleton className="h-10 w-full" />
|
||||
</div>
|
||||
<Skeleton className="h-10 w-32 ml-4" />
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
{[1, 2, 3].map((i) => (
|
||||
<div key={i} className="border rounded-lg p-4">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="flex-1 min-w-0 space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Skeleton className="h-4 w-4" />
|
||||
<Skeleton className="h-5 w-48" />
|
||||
<Skeleton className="h-5 w-20" />
|
||||
</div>
|
||||
<Skeleton className="h-4 w-64" />
|
||||
<div className="space-y-1">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<Skeleton className="h-5 w-24" />
|
||||
<Skeleton className="h-4 w-20" />
|
||||
</div>
|
||||
<Skeleton className="h-4 w-16" />
|
||||
</div>
|
||||
</div>
|
||||
<Skeleton className="h-8 w-8" />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
export const KnowledgeBaseManager = ({ threadId }: KnowledgeBaseManagerProps) => {
|
||||
const [editDialog, setEditDialog] = useState<EditDialogData>({ isOpen: false });
|
||||
const [deleteEntryId, setDeleteEntryId] = useState<string | null>(null);
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [formData, setFormData] = useState<CreateKnowledgeBaseEntryRequest>({
|
||||
name: '',
|
||||
description: '',
|
||||
content: '',
|
||||
usage_context: 'always',
|
||||
});
|
||||
|
||||
const { data: knowledgeBase, isLoading, error } = useKnowledgeBaseEntries(threadId);
|
||||
const createMutation = useCreateKnowledgeBaseEntry();
|
||||
const updateMutation = useUpdateKnowledgeBaseEntry();
|
||||
const deleteMutation = useDeleteKnowledgeBaseEntry();
|
||||
|
||||
const handleOpenCreateDialog = () => {
|
||||
setFormData({
|
||||
name: '',
|
||||
description: '',
|
||||
content: '',
|
||||
usage_context: 'always',
|
||||
});
|
||||
setEditDialog({ isOpen: true });
|
||||
};
|
||||
|
||||
const handleOpenEditDialog = (entry: KnowledgeBaseEntry) => {
|
||||
setFormData({
|
||||
name: entry.name,
|
||||
description: entry.description || '',
|
||||
content: entry.content,
|
||||
usage_context: entry.usage_context,
|
||||
});
|
||||
setEditDialog({ entry, isOpen: true });
|
||||
};
|
||||
|
||||
const handleCloseDialog = () => {
|
||||
setEditDialog({ isOpen: false });
|
||||
setFormData({
|
||||
name: '',
|
||||
description: '',
|
||||
content: '',
|
||||
usage_context: 'always',
|
||||
});
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (!formData.name.trim() || !formData.content.trim()) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (editDialog.entry) {
|
||||
const updateData: UpdateKnowledgeBaseEntryRequest = {
|
||||
name: formData.name !== editDialog.entry.name ? formData.name : undefined,
|
||||
description: formData.description !== editDialog.entry.description ? formData.description : undefined,
|
||||
content: formData.content !== editDialog.entry.content ? formData.content : undefined,
|
||||
usage_context: formData.usage_context !== editDialog.entry.usage_context ? formData.usage_context : undefined,
|
||||
};
|
||||
const hasChanges = Object.values(updateData).some(value => value !== undefined);
|
||||
if (hasChanges) {
|
||||
await updateMutation.mutateAsync({ entryId: editDialog.entry.entry_id, data: updateData });
|
||||
}
|
||||
} else {
|
||||
await createMutation.mutateAsync({ threadId, data: formData });
|
||||
}
|
||||
|
||||
handleCloseDialog();
|
||||
} catch (error) {
|
||||
console.error('Error saving knowledge base entry:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (entryId: string) => {
|
||||
try {
|
||||
await deleteMutation.mutateAsync(entryId);
|
||||
setDeleteEntryId(null);
|
||||
} catch (error) {
|
||||
console.error('Error deleting knowledge base entry:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleToggleActive = async (entry: KnowledgeBaseEntry) => {
|
||||
try {
|
||||
await updateMutation.mutateAsync({
|
||||
entryId: entry.entry_id,
|
||||
data: { is_active: !entry.is_active }
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error toggling entry status:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const getUsageContextConfig = (context: string) => {
|
||||
return USAGE_CONTEXT_OPTIONS.find(option => option.value === context) || USAGE_CONTEXT_OPTIONS[0];
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return <KnowledgeBaseSkeleton />;
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<div className="text-center">
|
||||
<AlertCircle className="h-8 w-8 text-red-500 mx-auto mb-4" />
|
||||
<p className="text-sm text-red-600 dark:text-red-400">Failed to load knowledge base</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const entries = knowledgeBase?.entries || [];
|
||||
const filteredEntries = entries.filter(entry =>
|
||||
entry.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||
entry.content.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||
(entry.description && entry.description.toLowerCase().includes(searchQuery.toLowerCase()))
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{entries.length > 0 && (
|
||||
<>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="relative w-full">
|
||||
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search knowledge entries..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="pl-9"
|
||||
/>
|
||||
</div>
|
||||
<Button onClick={handleOpenCreateDialog} className="gap-2 ml-4">
|
||||
<Plus className="h-4 w-4" />
|
||||
Add Knowledge
|
||||
</Button>
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
{filteredEntries.length === 0 ? (
|
||||
<div className="text-center py-8">
|
||||
<Search className="h-8 w-8 mx-auto text-muted-foreground/50 mb-2" />
|
||||
<p className="text-sm text-muted-foreground">No entries match your search</p>
|
||||
</div>
|
||||
) : (
|
||||
filteredEntries.map((entry) => {
|
||||
const contextConfig = getUsageContextConfig(entry.usage_context);
|
||||
const ContextIcon = contextConfig.icon;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={entry.entry_id}
|
||||
className={cn(
|
||||
"group border rounded-lg p-4 transition-all",
|
||||
entry.is_active
|
||||
? "border-border bg-card hover:border-border/80"
|
||||
: "border-border/50 bg-muted/30 opacity-70"
|
||||
)}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="flex-1 min-w-0 space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<FileText className="h-4 w-4 text-muted-foreground flex-shrink-0" />
|
||||
<h3 className="font-medium truncate">{entry.name}</h3>
|
||||
{!entry.is_active && (
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
<EyeOff className="h-3 w-3 mr-1" />
|
||||
Disabled
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
{entry.description && (
|
||||
<p className="text-sm text-muted-foreground line-clamp-1">
|
||||
{entry.description}
|
||||
</p>
|
||||
)}
|
||||
<p className="text-sm text-foreground/80 line-clamp-2 leading-relaxed">
|
||||
{entry.content}
|
||||
</p>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<Badge variant="outline" className={cn("text-xs gap-1", contextConfig.color)}>
|
||||
<ContextIcon className="h-3 w-3" />
|
||||
{contextConfig.label}
|
||||
</Badge>
|
||||
<span className="text-xs text-muted-foreground flex items-center gap-1">
|
||||
<Clock className="h-3 w-3" />
|
||||
{new Date(entry.created_at).toLocaleDateString()}
|
||||
</span>
|
||||
</div>
|
||||
{entry.content_tokens && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
~{entry.content_tokens.toLocaleString()} tokens
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0 opacity-0 group-hover:opacity-100 transition-opacity"
|
||||
>
|
||||
<MoreVertical className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-36">
|
||||
<DropdownMenuItem onClick={() => handleOpenEditDialog(entry)}>
|
||||
<Edit2 className="h-4 w-4" />
|
||||
Edit
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => handleToggleActive(entry)}>
|
||||
{entry.is_active ? (
|
||||
<>
|
||||
<EyeOff className="h-4 w-4" />
|
||||
Disable
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Eye className="h-4 w-4" />
|
||||
Enable
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
onClick={() => setDeleteEntryId(entry.entry_id)}
|
||||
className="text-destructive focus:bg-destructive/10 focus:text-destructive"
|
||||
>
|
||||
<Trash2 className="h-4 w-4 text-destructive" />
|
||||
Delete
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{entries.length === 0 && (
|
||||
<div className="text-center py-12">
|
||||
<div className="mx-auto w-24 h-24 bg-muted/50 rounded-full flex items-center justify-center mb-4">
|
||||
<FileText className="h-8 w-8 text-muted-foreground" />
|
||||
</div>
|
||||
<h3 className="text-lg font-medium mb-2">No Knowledge Entries</h3>
|
||||
<p className="text-muted-foreground mb-6 max-w-md mx-auto">
|
||||
Add knowledge entries to provide your agent with context, guidelines, and information it should always remember.
|
||||
</p>
|
||||
<Button onClick={handleOpenCreateDialog} className="gap-2">
|
||||
<Plus className="h-4 w-4" />
|
||||
Create Your First Entry
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Dialog open={editDialog.isOpen} onOpenChange={handleCloseDialog}>
|
||||
<DialogContent className="max-w-2xl max-h-[85vh] overflow-hidden flex flex-col">
|
||||
<DialogHeader className="flex-shrink-0">
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<FileText className="h-5 w-5" />
|
||||
{editDialog.entry ? 'Edit Knowledge Entry' : 'Add Knowledge Entry'}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
<form onSubmit={handleSubmit} className="space-y-6 p-1">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="name" className="text-sm font-medium">Name *</Label>
|
||||
<Input
|
||||
id="name"
|
||||
value={formData.name}
|
||||
onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
|
||||
placeholder="e.g., Company Guidelines, API Documentation"
|
||||
required
|
||||
className="w-full"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="usage_context" className="text-sm font-medium">Usage Context</Label>
|
||||
<Select
|
||||
value={formData.usage_context}
|
||||
onValueChange={(value: 'always' | 'on_request' | 'contextual') =>
|
||||
setFormData(prev => ({ ...prev, usage_context: value }))
|
||||
}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{USAGE_CONTEXT_OPTIONS.map((option) => {
|
||||
const Icon = option.icon;
|
||||
return (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
<div className="flex items-center gap-2">
|
||||
<Icon className="h-4 w-4" />
|
||||
<div>
|
||||
<div className="font-medium">{option.label}</div>
|
||||
</div>
|
||||
</div>
|
||||
</SelectItem>
|
||||
);
|
||||
})}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="description" className="text-sm font-medium">Description</Label>
|
||||
<Input
|
||||
id="description"
|
||||
value={formData.description}
|
||||
onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))}
|
||||
placeholder="Brief description of this knowledge (optional)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="content" className="text-sm font-medium">Content *</Label>
|
||||
<Textarea
|
||||
id="content"
|
||||
value={formData.content}
|
||||
onChange={(e) => setFormData(prev => ({ ...prev, content: e.target.value }))}
|
||||
placeholder="Enter the knowledge content that your agent should know..."
|
||||
className="min-h-[200px] resize-y"
|
||||
required
|
||||
/>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
Approximately {Math.ceil(formData.content.length / 4).toLocaleString()} tokens
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-3 pt-4 border-t">
|
||||
<Button type="button" variant="outline" onClick={handleCloseDialog}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={!formData.name.trim() || !formData.content.trim() ||
|
||||
createMutation.isPending || updateMutation.isPending}
|
||||
className="gap-2"
|
||||
>
|
||||
{createMutation.isPending || updateMutation.isPending ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Plus className="h-4 w-4" />
|
||||
)}
|
||||
{editDialog.entry ? 'Save Changes' : 'Add Knowledge'}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
<AlertDialog open={!!deleteEntryId} onOpenChange={() => setDeleteEntryId(null)}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle className="flex items-center gap-2">
|
||||
<AlertCircle className="h-5 w-5 text-destructive" />
|
||||
Delete Knowledge Entry
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
This will permanently delete this knowledge entry. Your agent will no longer have access to this information.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={() => deleteEntryId && handleDelete(deleteEntryId)}
|
||||
className="bg-destructive hover:bg-destructive/90"
|
||||
disabled={deleteMutation.isPending}
|
||||
>
|
||||
{deleteMutation.isPending ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Trash2 className="h-4 w-4" />
|
||||
)}
|
||||
Delete Entry
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
);
|
||||
}
|
|
@ -21,7 +21,6 @@ import { ShareModal } from "@/components/sidebar/share-modal"
|
|||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { projectKeys } from "@/hooks/react-query/sidebar/keys";
|
||||
import { threadKeys } from "@/hooks/react-query/threads/keys";
|
||||
import { KnowledgeBaseManager } from "@/components/thread/knowledge-base/knowledge-base-manager";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
|
@ -231,23 +230,6 @@ export function SiteHeader({
|
|||
</TooltipContent>
|
||||
</Tooltip>
|
||||
|
||||
{knowledgeBaseEnabled && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={openKnowledgeBase}
|
||||
className="h-9 w-9 cursor-pointer"
|
||||
>
|
||||
<Book className="h-4 w-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>Knowledge Base</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
|
@ -290,21 +272,6 @@ export function SiteHeader({
|
|||
projectId={projectId}
|
||||
/>
|
||||
|
||||
<Dialog open={showKnowledgeBase} onOpenChange={setShowKnowledgeBase}>
|
||||
<DialogContent className="max-w-2xl max-h-[90vh] overflow-hidden p-0">
|
||||
<div className="flex flex-col h-full">
|
||||
<DialogHeader className="px-6 py-4">
|
||||
<DialogTitle className="flex items-center gap-2 text-lg">
|
||||
<Book className="h-5 w-5" />
|
||||
Knowledge Base
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="flex-1 overflow-y-auto p-6">
|
||||
<KnowledgeBaseManager threadId={threadId} />
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
)
|
||||
}
|
|
@ -7,6 +7,5 @@ export const knowledgeBaseKeys = {
|
|||
entry: (entryId: string) => [...knowledgeBaseKeys.all, 'entry', entryId] as const,
|
||||
context: (threadId: string) => [...knowledgeBaseKeys.all, 'context', threadId] as const,
|
||||
agentContext: (agentId: string) => [...knowledgeBaseKeys.all, 'agent-context', agentId] as const,
|
||||
combinedContext: (threadId: string, agentId?: string) => [...knowledgeBaseKeys.all, 'combined-context', threadId, agentId] as const,
|
||||
processingJobs: (agentId: string) => [...knowledgeBaseKeys.all, 'processing-jobs', agentId] as const,
|
||||
};
|
|
@ -34,28 +34,6 @@ const useAuthHeaders = () => {
|
|||
return { getHeaders };
|
||||
};
|
||||
|
||||
export function useKnowledgeBaseEntries(threadId: string, includeInactive = false) {
|
||||
const { getHeaders } = useAuthHeaders();
|
||||
|
||||
return useQuery({
|
||||
queryKey: knowledgeBaseKeys.thread(threadId),
|
||||
queryFn: async (): Promise<KnowledgeBaseListResponse> => {
|
||||
const headers = await getHeaders();
|
||||
const url = new URL(`${API_URL}/knowledge-base/threads/${threadId}`);
|
||||
url.searchParams.set('include_inactive', includeInactive.toString());
|
||||
|
||||
const response = await fetch(url.toString(), { headers });
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.text();
|
||||
throw new Error(error || 'Failed to fetch knowledge base entries');
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
},
|
||||
enabled: !!threadId,
|
||||
});
|
||||
}
|
||||
|
||||
export function useKnowledgeBaseEntry(entryId: string) {
|
||||
const { getHeaders } = useAuthHeaders();
|
||||
|
@ -77,63 +55,6 @@ export function useKnowledgeBaseEntry(entryId: string) {
|
|||
});
|
||||
}
|
||||
|
||||
export function useKnowledgeBaseContext(threadId: string, maxTokens = 4000) {
|
||||
const { getHeaders } = useAuthHeaders();
|
||||
|
||||
return useQuery({
|
||||
queryKey: knowledgeBaseKeys.context(threadId),
|
||||
queryFn: async () => {
|
||||
const headers = await getHeaders();
|
||||
const url = new URL(`${API_URL}/knowledge-base/threads/${threadId}/context`);
|
||||
url.searchParams.set('max_tokens', maxTokens.toString());
|
||||
|
||||
const response = await fetch(url.toString(), { headers });
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.text();
|
||||
throw new Error(error || 'Failed to fetch knowledge base context');
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
},
|
||||
enabled: !!threadId,
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateKnowledgeBaseEntry() {
|
||||
const queryClient = useQueryClient();
|
||||
const { getHeaders } = useAuthHeaders();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async ({ threadId, data }: { threadId: string; data: CreateKnowledgeBaseEntryRequest }) => {
|
||||
const headers = await getHeaders();
|
||||
const response = await fetch(`${API_URL}/knowledge-base/threads/${threadId}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...headers,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.text();
|
||||
throw new Error(error || 'Failed to create knowledge base entry');
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
},
|
||||
onSuccess: (_, { threadId }) => {
|
||||
queryClient.invalidateQueries({ queryKey: knowledgeBaseKeys.thread(threadId) });
|
||||
queryClient.invalidateQueries({ queryKey: knowledgeBaseKeys.context(threadId) });
|
||||
toast.success('Knowledge base entry created successfully');
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error(`Failed to create knowledge base entry: ${error.message}`);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdateKnowledgeBaseEntry() {
|
||||
const queryClient = useQueryClient();
|
||||
const { getHeaders } = useAuthHeaders();
|
||||
|
@ -276,32 +197,6 @@ export function useAgentKnowledgeBaseContext(agentId: string, maxTokens = 4000)
|
|||
});
|
||||
}
|
||||
|
||||
export function useCombinedKnowledgeBaseContext(threadId: string, agentId?: string, maxTokens = 4000) {
|
||||
const { getHeaders } = useAuthHeaders();
|
||||
|
||||
return useQuery({
|
||||
queryKey: knowledgeBaseKeys.combinedContext(threadId, agentId),
|
||||
queryFn: async () => {
|
||||
const headers = await getHeaders();
|
||||
const url = new URL(`${API_URL}/knowledge-base/threads/${threadId}/combined-context`);
|
||||
url.searchParams.set('max_tokens', maxTokens.toString());
|
||||
if (agentId) {
|
||||
url.searchParams.set('agent_id', agentId);
|
||||
}
|
||||
|
||||
const response = await fetch(url.toString(), { headers });
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.text();
|
||||
throw new Error(error || 'Failed to fetch combined knowledge base context');
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
},
|
||||
enabled: !!threadId,
|
||||
});
|
||||
}
|
||||
|
||||
// New hooks for file upload and git clone operations
|
||||
export function useUploadAgentFiles() {
|
||||
const queryClient = useQueryClient();
|
||||
|
|
|
@ -3,10 +3,10 @@
|
|||
async function installSunaForNewUser(userId: string) {
|
||||
try {
|
||||
const backendUrl = process.env.NEXT_PUBLIC_BACKEND_URL;
|
||||
const adminApiKey = process.env.ADMIN_API_KEY;
|
||||
const adminApiKey = process.env.KORTIX_ADMIN_API_KEY;
|
||||
|
||||
if (!adminApiKey) {
|
||||
console.error('ADMIN_API_KEY not configured - cannot install Suna agent');
|
||||
console.error('KORTIX_ADMIN_API_KEY not configured - cannot install Suna agent');
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in New Issue