메인 콘텐츠로 건너뛰기
Memory API는 쿼리에 대해 최적의 컨텍스트를 자동으로 조립합니다. 시맨틱 검색, 그래프 탐색, 에피소드 이력을 조합하여 LLM에 전달할 정보를 구축합니다.

개요

const client = new NdxClient({
  apiKey: process.env.NEURADEX_API_KEY,
  projectId: 'your-project-id',
});

// Memory API 접근
const context = await client.memory.getContext('쿼리');
const related = await client.memory.exploreRelated('knowledge-id');

메서드 목록

메서드설명
getContext(query, options?)쿼리에 대한 컨텍스트 가져오기
exploreRelated(knowledgeId, options?)관련 지식 탐색

getContext()

쿼리에 대해 최적화된 컨텍스트를 조립합니다.

처리 흐름

  1. 시맨틱 검색: 쿼리와 관련된 지식 검색
  2. 그래프 탐색: 관련 지식을 다단계로 탐색
  3. 에피소드 조회: 관련 Q&A 이력과 변경 이력 조회
  4. 최적화: 토큰 예산 내에 맞게 결과 조정
  5. 포맷팅: LLM에 전달할 형식으로 정형화

파라미터

query
string
필수
검색 쿼리 (자연어)
options.tokenBudget
number
기본값:"8000"
컨텍스트 최대 토큰 수
options.includeEpisodes
boolean
기본값:"true"
Q&A 이력 등 에피소드 포함 여부
관련 지식 포함 여부
options.maxDepth
number
기본값:"2"
그래프 탐색 최대 깊이

반환값

interface Context {
  items: ContextItem[];     // 컨텍스트 구성 요소
  totalTokens: number;      // 총 토큰 수
  truncated: boolean;       // 예산 초과로 잘렸는지
  formatted: string;        // LLM에 전달할 형식의 문자열
}

interface ContextItem {
  type: 'knowledge' | 'related' | 'episode';
  id: string;
  title?: string;
  content: string;
  score: number;
  tokens: number;
}

사용 예

// 기본 사용
const context = await client.memory.getContext('반품 절차를 알려주세요');

console.log(`토큰 수: ${context.totalTokens}`);
console.log(`잘림 여부: ${context.truncated}`);

// LLM 프롬프트에 포함
const prompt = `
다음 정보를 참고하여 사용자의 질문에 답변해 주세요.

## 참고 정보
${context.formatted}

## 질문
반품 절차를 알려주세요
`;

옵션 조정

// 토큰 예산 제한
const context = await client.memory.getContext('질문', {
  tokenBudget: 2000,  // 작은 모델용
});

// 에피소드 제외 (지식만)
const context = await client.memory.getContext('질문', {
  includeEpisodes: false,
});

// 얕은 탐색 (직접 관련만)
const context = await client.memory.getContext('질문', {
  maxDepth: 1,
});

// 깊은 탐색 (더 많은 관련 정보)
const context = await client.memory.getContext('질문', {
  maxDepth: 3,
  tokenBudget: 16000,
});

컨텍스트 아이템 확인

const context = await client.memory.getContext('질문');

// 유형별 아이템 확인
const knowledge = context.items.filter(item => item.type === 'knowledge');
const related = context.items.filter(item => item.type === 'related');
const episodes = context.items.filter(item => item.type === 'episode');

console.log(`직접 히트: ${knowledge.length}개`);
console.log(`관련 지식: ${related.length}개`);
console.log(`에피소드: ${episodes.length}개`);

// 점수순 표시
for (const item of context.items.sort((a, b) => b.score - a.score)) {
  console.log(`[${item.type}] ${item.title ?? item.id} (${item.score.toFixed(2)})`);
}

exploreRelated()

지정된 지식에서 관련 지식을 탐색합니다. Multi-hop 탐색(BFS)으로 직접 연결되지 않은 지식도 발견할 수 있습니다.

파라미터

knowledgeId
string
필수
시작점 지식 ID
options.maxDepth
number
기본값:"2"
탐색 최대 깊이

반환값

interface ExploreResult {
  relatedNodes: RelatedKnowledge[];  // 발견한 지식
  paths: GraphPath[];                 // 발견한 경로
  depth: number;                      // 실제 탐색 깊이
}

interface RelatedKnowledge {
  id: string;
  title: string;
  content: string;
  path: GraphPath;  // 이 지식으로의 경로
}

interface GraphPath {
  nodeIds: string[];    // 경로상의 지식 ID
  edgeIds: string[];    // 경로상의 엣지 ID
  totalWeight: number;  // 경로의 총 가중치
}

사용 예

// 관련 지식 탐색
const result = await client.memory.exploreRelated('knowledge-id');

console.log(`발견한 지식: ${result.relatedNodes.length}개`);
console.log(`탐색 깊이: ${result.depth}`);

// 발견한 지식 표시
for (const node of result.relatedNodes) {
  const hops = node.path.nodeIds.length - 1;
  console.log(`${node.title} (${hops}홉)`);
}

깊은 탐색

// 더 넓은 범위 탐색
const result = await client.memory.exploreRelated('knowledge-id', {
  maxDepth: 3,
});

// 홉 수별 분류
const byHops = new Map<number, RelatedKnowledge[]>();
for (const node of result.relatedNodes) {
  const hops = node.path.nodeIds.length - 1;
  if (!byHops.has(hops)) byHops.set(hops, []);
  byHops.get(hops)!.push(node);
}

for (const [hops, nodes] of byHops) {
  console.log(`${hops}홉: ${nodes.length}개`);
}

유스케이스

RAG 애플리케이션

import { NdxClient } from '@neuradex/sdk';
import OpenAI from 'openai';

const neuradex = new NdxClient({
  apiKey: process.env.NEURADEX_API_KEY,
  projectId: process.env.NEURADEX_PROJECT_ID,
});
const openai = new OpenAI();

async function askQuestion(question: string): Promise<string> {
  // 컨텍스트 가져오기
  const context = await neuradex.memory.getContext(question, {
    tokenBudget: 4000,
    includeEpisodes: true,
  });

  // LLM으로 답변 생성
  const response = await openai.chat.completions.create({
    model: 'gpt-4o',
    messages: [
      {
        role: 'system',
        content: `당신은 어시스턴트입니다. 다음 정보를 참고하여 답변해 주세요.

${context.formatted}`,
      },
      { role: 'user', content: question },
    ],
  });

  return response.choices[0].message.content ?? '';
}

지식 그래프 시각화

async function buildGraph(startId: string) {
  const result = await client.memory.exploreRelated(startId, {
    maxDepth: 2,
  });

  // 그래프 데이터 구축
  const nodes = new Map<string, { id: string; title: string }>();
  const edges: Array<{ from: string; to: string }> = [];

  for (const related of result.relatedNodes) {
    nodes.set(related.id, { id: related.id, title: related.title });

    // 경로에서 엣지 추출
    const path = related.path.nodeIds;
    for (let i = 0; i < path.length - 1; i++) {
      edges.push({ from: path[i], to: path[i + 1] });
    }
  }

  return {
    nodes: Array.from(nodes.values()),
    edges,
  };
}

다음 단계

Knowledge API

지식 관리

Episodes API

이벤트·이력 기록