HanaSparqlQAAgent를 이용한 질의응답

HanaSparqlQAAgent를 이용한 질의응답 (Question Answering with HanaSparqlQAAgent)

LangChain JavaScript를 사용하여 HanaSparqlQAAgent 유형과 통합합니다.

설정 및 설치

이 기능을 사용하려면 @sap/hana-langchain 패키지와 피어 의존성을 설치하세요:

npm install @sap/hana-langchain @langchain/core@latest @langchain/classic@latest langchain@latest

HanaSparqlQAAgent는 SAP HANA Cloud에 저장된 RDF 데이터에 대한 질문에 답하는 에이전트 기반 접근 방식입니다. 체인 기반 접근 방식과 달리 에이전트는 다음과 같은 일을 할 수 있습니다.

  1. 전용 도구를 사용해 온톨로지를 동적으로 검색
  2. SPARQL 쿼리를 반복적으로 생성하고 실행
  3. 쿼리가 실패하거나 예상치 못한 결과를 반환하면 자체 수정
  4. 복잡한 질문에 대해 단계별로 추론

초기화

다음이 필요합니다:

  • 에이전트의 추론을 구동할 LLM
  • (연결, graphUri, 온톨로지를 갖춘) HanaRdfGraph

HanaRdfGraph 인스턴스 만드는 방법에 대해 자세히 알아보려면 HanaRdfGraph의 단계를 따르세요.

HanaSparqlQAAgent를 임포트합니다.

import { HanaSparqlQAAgent, HanaSparqlQAAgentOptions } from "@sap/hana-langchain";
const agentConfig : HanaSparqlQAAgentOptions = {
  graph: graph
};
const agent = HanaSparqlQAAgent.createAgent(llm, agentConfig);

에이전트 개요

에이전트는 도구를 반복적으로 사용하여:

  1. 먼저 온톨로지를 검색해 데이터 구조를 이해합니다.
  2. 스키마에 기반해 적절한 SPARQL 쿼리를 생성합니다.
  3. 쿼리를 실행하고 결과를 해석합니다.
  4. 자연어 답변을 구성합니다.

기본값

  • 도구:
    • retrieveOntology - 그래프에서 RDF 온톨로지/스키마를 Turtle 형식으로 검색합니다.
    • executeSparql - HANA RDF 그래프에 대해 SPARQL 쿼리를 실행합니다.
  • 시스템 프롬프트: SPARQL 생성 및 도구 사용에 대한 지침이 포함된 기본 시스템 프롬프트가 제공됩니다.
  • 미들웨어: 무한 루프를 방지하기 위해 ModelRetryMiddleware({maxRetries:3})ToolRetryMiddleWare({maxRetries:2})가 기본으로 추가됩니다.

에이전트 커스터마이징

createAgent에 추가 파라미터를 제공하여 에이전트의 동작을 커스터마이즈할 수 있습니다:

const agentConfig : HanaSparqlQAAgentOptions = {
  graph: graph,  // Required: HanaRdfGraph instance
  systemPrompt: yourCustomPrompt,  // Custom system prompt (string or SystemMessage)
  tools: [yourCustomTools],  // Additional tools to include
  middleware: [yourCustomMiddlewares],  // Additional middleware to include
  includeDefaultTools: true,  // include default tools (default: True)
  includeDefaultMiddleware: true,  // include default middleware (default: True)
};
const agent = HanaSparqlQAAgent.createAgent(
    model, // Required LLM to power the agent
    agentConfig
)

예시: "Movies" 지식 그래프에 대한 질의응답

전제 조건: triple store 기능이 활성화된 SAP HANA Cloud 인스턴스가 있어야 합니다. 자세한 지침은 Triple Store 활성화를 참조하세요.
kgdocu_movies 예시 데이터를 로드하세요. Knowledge Graph 예시를 참조하세요.

아래 예시는:

  1. movies 데이터 그래프를 가리키는 HanaRdfGraph를 인스턴스화하고
  2. LLM이 지원하는 HanaSparqlQAAgent를 만들고
  3. 자연어 질문을 하고 에이전트가 답을 추론하게 합니다.

이것은 에이전트가 온톨로지를 동적으로 검색하고, SPARQL 쿼리를 생성하며, 사람이 읽을 수 있는 답변을 반환하는 방법을 보여 줍니다.

import * as dotenv from 'dotenv';
// Load environment variables if needed
dotenv.config();

import hanaClient from "@sap/hana-client";

const connectionParams = {
  host: process.env.HANA_DB_ADDRESS,
  port: process.env.HANA_DB_PORT,
  user: process.env.HANA_DB_USER,
  password: process.env.HANA_DB_PASSWORD,
};
const client = hanaClient.createConnection(connectionParams);

// connect to hanaDB
await new Promise<void>((resolve, reject) => {
  client.connect((err: Error) => {
    // Use arrow function here
    if (err) {
      reject(err);
    } else {
      console.log("Connected to SAP HANA successfully.");
      resolve();
    }
  });
});

그런 다음 지식 그래프 인스턴스를 설정합니다.

import { HanaRdfGraph, HanaRdfGraphOptions } from "@sap/hana-langchain";

const graphOptions: HanaRdfGraphOptions = {
  connection: client,
  graphUri: "kgdocu_movies",
  autoExtractOntology: true,
};

// create a Graph instance from a source URI
const graph = new HanaRdfGraph(graphOptions);

// need to initialize once an instance is created.
await graph.initialize(graphOptions);
// Serialise the graph schema (optional)
// Internally, the schema is stored as an N3 Store instance,
// We use the N3 Writer to serialise it to Turtle format for display.
const schemaStore = graph.getSchema();
const writer = new Writer({
  prefixes: {
    rdf: "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
    rdfs: "http://www.w3.org/2000/01/rdf-schema#",
    owl: "http://www.w3.org/2002/07/owl#",
    xsd: "http://www.w3.org/2001/XMLSchema#",
  },
});
schemaStore.forEach((quad) => {
  writer.addQuad(quad);
});
writer.end((error, result) => {
  if (error) {
    console.error("Error serialising schema:", error);
  } else {
    console.log("Graph Schema in Turtle format:\n", result);
  }
});

그런 다음 LLM을 초기화합니다.

import { ChatOpenAI } from "@langchain/openai"; // or your chosen LLM
// import { AzureOpenAiChatClient } from "@sap-ai-sdk/langchain";

const llm = new ChatOpenAI({ model: "gpt-4o" });
// const llm = new AzureOpenAiChatClient({ modelName: "gpt-4o" });

그 후 SPARQL QA Agent를 만듭니다.

const agentConfig: HanaSparqlQAAgentOptions = {
  graph: graph,
};

// Initialize the QA agent
const agent = HanaSparqlQAAgent.createAgent(llm, agentConfig);
const query = "which actors acted in Blade Runner?";
// const query = "Which movies are in the data?"
// const query = "In which movies did Keanu Reeves and Carrie-Anne Moss play in together"
// const query = "which movie genres are in the data?"
// const query = "which are the two most assigned movie genres?"
// const query = "where were the actors of 'Blade Runner' born?"
// const query = "which actors acted together in a movie and were born in the same city?"

console.log("\n--- Streamed (messages: token-by-token) ---");
for await (const [chunk, _metadata] of await agent.stream(
  { messages: [{ role: "user", content: query }] },
  { streamMode: "messages" }
)) {
  if (chunk.content) {
    process.stdout.write(chunk.text);
  }
}
console.log();

내부에서 무슨 일이 일어나나요?

  1. 온톨로지 검색 에이전트는 먼저 retrieveOntology 도구를 사용해 RDF 스키마를 Turtle 형식으로 가져옵니다. 이를 통해 사용 가능한 클래스, 속성, 관계를 이해할 수 있습니다.

  2. SPARQL 생성 온톨로지와 사용자 질문에 기반해 에이전트는 어떤 엔티티와 속성을 쿼리할지 추론한 다음 유효한 SELECT 쿼리를 생성합니다.

  3. 쿼리 실행 에이전트는 executeSparql 도구를 호출해 생성된 쿼리를 HANA RDF 그래프에 대해 실행합니다. 쿼리가 실패하거나 예상치 못한 결과를 반환하면 에이전트는 자체 수정하고 다시 시도할 수 있습니다.

  4. 답변 작성 에이전트는 쿼리 결과를 해석하고, 검색된 데이터에 엄격히 기반하여 간결하고 사람이 읽을 수 있는 답변을 구성합니다.

더 알아보기

출처: 문서