cognee: 지식 그래프 기반 RAG 구성, 핵심 프롬프트 학습을 위한 오픈 소스 프레임워크

최신 AI 리소스7개월 전 업데이트 AI 공유 서클
3.1K 00

일반 소개

Cognee는 AI 애플리케이션과 AI 에이전트를 위해 설계된 신뢰할 수 있는 데이터 레이어 솔루션입니다. LLM(대규모 언어 모델) 컨텍스트를 로드하고 구축하여 지식 그래프와 벡터 스토어를 통해 정확하고 해석 가능한 AI 솔루션을 생성하도록 설계되었습니다. 이 프레임워크는 비용 절감, 해석 가능성 및 사용자 가이드 제어를 용이하게 하여 연구 및 교육용으로 적합합니다. 공식 웹사이트에서는 입문 튜토리얼, 개념 개요, 학습 자료 및 관련 연구 정보를 제공합니다.

코그니의 가장 큰 강점은 데이터를 던져주면 자동으로 처리하여 지식 그래프를 만들고 관련 주제들의 그래프를 다시 연결하여 데이터의 연관성을 더 잘 발견할 수 있도록 도와주는 것 같습니다. RAG LLM과 관련하여 최고의 해석 가능성을 제공합니다.

1. 데이터를 추가하고, LLM을 기반으로 데이터를 자동으로 식별 및 처리하고, 지식 그래프로 추출하고, 위베이트를 저장할 수 있습니다. 벡터 데이터베이스 2. 장점: 비용 절감, 해석 가능성 - 데이터의 그래픽 시각화, 제어 가능성 - 코드에 통합 등.

cognee:基于知识图谱构建的RAG开源框架,核心prompts学习

 

기능 목록

  • ECL 배관데이터 추출, 인식 및 로딩을 가능하게 하고, 과거 데이터의 상호 연결 및 검색을 지원합니다.
  • 다중 데이터베이스 지원PostgreSQL, Weaviate, Qdrant, Neo4j, Milvus 및 기타 데이터베이스를 지원합니다.
  • 환각 감소파이프라인 설계 최적화를 통한 AI 애플리케이션의 팬텀 현상 감소.
  • 개발자 친화적개발자의 문턱을 낮추기 위해 자세한 문서와 예제를 제공합니다.
  • 확장성간편한 확장 및 사용자 지정을 위한 모듈식 디자인.

 

도움말 사용

설치 프로세스

  1. pip를 사용하여 설치::
    pip install cognee
    

    또는 특정 데이터베이스 지원을 설치하세요:

    pip install 'cognee[<database>]'
    

    예를 들어 PostgreSQL 및 Neo4j 지원을 설치합니다:

    pip install 'cognee[postgres, neo4j]'
    
  2. 시를 이용한 설치::
    poetry add cognee
    

    또는 특정 데이터베이스 지원을 설치하세요:

    poetry add cognee -E <database>
    

    예를 들어 PostgreSQL 및 Neo4j 지원을 설치합니다:

    poetry add cognee -E postgres -E neo4j
    

사용 프로세스

  1. API 키 설정::
    import os
    os.environ["LLM_API_KEY"] = "YOUR_OPENAI_API_KEY"
    

    또는:

    import cognee
    cognee.config.set_llm_api_key("YOUR_OPENAI_API_KEY")
    
  2. .env 파일 만들기.env 파일을 만들고 API 키를 설정합니다:
    LLM_API_KEY=YOUR_OPENAI_API_KEY
    
  3. 다른 LLM 제공업체 사용다른 LLM 제공업체를 구성하는 방법을 알아보려면 문서를 참조하세요.
  4. 시각화 결과네트워크를 사용하는 경우 Graphistry 계정을 생성하고 구성합니다:
    cognee.config.set_graphistry_config({
    "username": "YOUR_USERNAME",
    "password": "YOUR_PASSWORD"
    })
    

주요 기능

  1. 데이터 추출여러 데이터 소스와 형식을 지원하는 Cognee의 ECL 파이프라인을 사용하여 데이터를 추출합니다.
  2. 데이터 인식환각을 줄이기 위해 코그니의 인지 모듈을 통해 데이터를 처리하고 분석합니다.
  3. 데이터 로드처리된 데이터를 대상 데이터베이스 또는 저장소로 로드하여 다양한 데이터베이스 및 벡터 저장소를 지원합니다.

주요 기능 작동 절차

  1. 과거 데이터의 상호 연결 및 검색Cognee의 모듈식 디자인을 사용하여 과거 대화, 문서 및 오디오 녹취록을 쉽게 상호 연결하고 검색할 수 있습니다.
  2. 개발자 업무량 감소자세한 문서와 예제를 제공하여 개발자의 문턱을 낮추고 개발 시간과 비용을 절감할 수 있습니다.

 

코그니 프레임에 대한 자세한 내용은 공식 웹사이트에서 확인하세요.
코그니의 이론적 기초를 마스터하는 방법에 대한 개요를 읽어보세요.
시작하기 위한 튜토리얼 및 학습 자료 보기

 

핵심 프롬프트 명령

분류_콘텐츠: 분류된 콘텐츠

You are a classification engine and should classify content. Make sure to use one of the existing classification options nad not invent your own.
The possible classifications are:
{
"Natural Language Text": {
"type": "TEXT",
"subclass": [
"Articles, essays, and reports",
"Books and manuscripts",
"News stories and blog posts",
"Research papers and academic publications",
"Social media posts and comments",
"Website content and product descriptions",
"Personal narratives and stories"
]
},
"Structured Documents": {
"type": "TEXT",
"subclass": [
"Spreadsheets and tables",
"Forms and surveys",
"Databases and CSV files"
]
},
"Code and Scripts": {
"type": "TEXT",
"subclass": [
"Source code in various programming languages",
"Shell commands and scripts",
"Markup languages (HTML, XML)",
"Stylesheets (CSS) and configuration files (YAML, JSON, INI)"
]
},
"Conversational Data": {
"type": "TEXT",
"subclass": [
"Chat transcripts and messaging history",
"Customer service logs and interactions",
"Conversational AI training data"
]
},
"Educational Content": {
"type": "TEXT",
"subclass": [
"Textbook content and lecture notes",
"Exam questions and academic exercises",
"E-learning course materials"
]
},
"Creative Writing": {
"type": "TEXT",
"subclass": [
"Poetry and prose",
"Scripts for plays, movies, and television",
"Song lyrics"
]
},
"Technical Documentation": {
"type": "TEXT",
"subclass": [
"Manuals and user guides",
"Technical specifications and API documentation",
"Helpdesk articles and FAQs"
]
},
"Legal and Regulatory Documents": {
"type": "TEXT",
"subclass": [
"Contracts and agreements",
"Laws, regulations, and legal case documents",
"Policy documents and compliance materials"
]
},
"Medical and Scientific Texts": {
"type": "TEXT",
"subclass": [
"Clinical trial reports",
"Patient records and case notes",
"Scientific journal articles"
]
},
"Financial and Business Documents": {
"type": "TEXT",
"subclass": [
"Financial reports and statements",
"Business plans and proposals",
"Market research and analysis reports"
]
},
"Advertising and Marketing Materials": {
"type": "TEXT",
"subclass": [
"Ad copies and marketing slogans",
"Product catalogs and brochures",
"Press releases and promotional content"
]
},
"Emails and Correspondence": {
"type": "TEXT",
"subclass": [
"Professional and formal correspondence",
"Personal emails and letters"
]
},
"Metadata and Annotations": {
"type": "TEXT",
"subclass": [
"Image and video captions",
"Annotations and metadata for various media"
]
},
"Language Learning Materials": {
"type": "TEXT",
"subclass": [
"Vocabulary lists and grammar rules",
"Language exercises and quizzes"
]
},
"Audio Content": {
"type": "AUDIO",
"subclass": [
"Music tracks and albums",
"Podcasts and radio broadcasts",
"Audiobooks and audio guides",
"Recorded interviews and speeches",
"Sound effects and ambient sounds"
]
},
"Image Content": {
"type": "IMAGE",
"subclass": [
"Photographs and digital images",
"Illustrations, diagrams, and charts",
"Infographics and visual data representations",
"Artwork and paintings",
"Screenshots and graphical user interfaces"
]
},
"Video Content": {
"type": "VIDEO",
"subclass": [
"Movies and short films",
"Documentaries and educational videos",
"Video tutorials and how-to guides",
"Animated features and cartoons",
"Live event recordings and sports broadcasts"
]
},
"Multimedia Content": {
"type": "MULTIMEDIA",
"subclass": [
"Interactive web content and games",
"Virtual reality (VR) and augmented reality (AR) experiences",
"Mixed media presentations and slide decks",
"E-learning modules with integrated multimedia",
"Digital exhibitions and virtual tours"
]
},
"3D Models and CAD Content": {
"type": "3D_MODEL",
"subclass": [
"Architectural renderings and building plans",
"Product design models and prototypes",
"3D animations and character models",
"Scientific simulations and visualizations",
"Virtual objects for AR/VR environments"
]
},
"Procedural Content": {
"type": "PROCEDURAL",
"subclass": [
"Tutorials and step-by-step guides",
"Workflow and process descriptions",
"Simulation and training exercises",
"Recipes and crafting instructions"
]
}
}

생성_코그_레이어: 인지 레이어 생성

You are tasked with analyzing `{{ data_type }}` files, especially in a multilayer network context for tasks such as analysis, categorization, and feature extraction. Various layers can be incorporated to capture the depth and breadth of information contained within the {{ data_type }}.

These layers can help in understanding the content, context, and characteristics of the `{{ data_type }}`.

Your objective is to extract meaningful layers of information that will contribute to constructing a detailed multilayer network or knowledge graph.

Approach this task by considering the unique characteristics and inherent properties of the data at hand.

VERY IMPORTANT: The context you are working in is `{{ category_name }}` and the specific domain you are extracting data on is `{{ category_name }}`.

Guidelines for Layer Extraction:
Take into account: The content type, in this case, is: `{{ category_name }}`, should play a major role in how you decompose into layers.

Based on your analysis, define and describe the layers you've identified, explaining their relevance and contribution to understanding the dataset. Your independent identification of layers will enable a nuanced and multifaceted representation of the data, enhancing applications in knowledge discovery, content analysis, and information retrieval.

GENERATE_GRAPH_PROMPT: 그래프 프롬프트 생성

You are a top-tier algorithm
designed for extracting information in structured formats to build a knowledge graph.
- **Nodes** represent entities and concepts. They're akin to Wikipedia nodes.
- **Edges** represent relationships between concepts. They're akin to Wikipedia links.
- The aim is to achieve simplicity and clarity in the
knowledge graph, making it accessible for a vast audience.
YOU ARE ONLY EXTRACTING DATA FOR COGNITIVE LAYER `{{ layer }}`
## 1. Labeling Nodes
- **Consistency**: Ensure you use basic or elementary types for node labels.
- For example, when you identify an entity representing a person,
always label it as **"Person"**.
Avoid using more specific terms like "mathematician" or "scientist".
- Include event, entity, time, or action nodes to the category.
- Classify the memory type as episodic or semantic.
- **Node IDs**: Never utilize integers as node IDs.
Node IDs should be names or human-readable identifiers found in the text.
## 2. Handling Numerical Data and Dates
- Numerical data, like age or other related information,
should be incorporated as attributes or properties of the respective nodes.
- **No Separate Nodes for Dates/Numbers**:
Do not create separate nodes for dates or numerical values.
Always attach them as attributes or properties of nodes.
- **Property Format**: Properties must be in a key-value format.
- **Quotation Marks**: Never use escaped single or double quotes within property values.
- **Naming Convention**: Use snake_case for relationship names, e.g., `acted_in`.
## 3. Coreference Resolution
- **Maintain Entity Consistency**:
When extracting entities, it's vital to ensure consistency.
If an entity, such as "John Doe", is mentioned multiple times
in the text but is referred to by different names or pronouns (e.g., "Joe", "he"),
always use the most complete identifier for that entity throughout the knowledge graph.
In this example, use "John Doe" as the entity ID.
Remember, the knowledge graph should be coherent and easily understandable,
so maintaining consistency in entity references is crucial.
## 4. Strict Compliance
Adhere to the rules strictly. Non-compliance will result in termination"""

 

READ_QUERY_PROMPT: 쿼리 프롬프트 읽기

from os import path
import logging
from cognee.root_dir import get_absolute_path

def read_query_prompt(prompt_file_name: str):
"""Read a query prompt from a file."""
try:
file_path = path.join(get_absolute_path("./infrastructure/llm/prompts"), prompt_file_name)

with open(file_path, "r", encoding = "utf-8") as file:
return file.read()
except FileNotFoundError:
logging.error(f"Error: Prompt file not found. Attempted to read: %s {file_path}")
return None
except Exception as e:
logging.error(f"An error occurred: %s {e}")
return None

 

렌더링_프롬프트: 프롬프트 렌더링

from jinja2 import Environment, FileSystemLoader, select_autoescape
from cognee.root_dir import get_absolute_path

def render_prompt(filename: str, context: dict) -> str:
"""Render a Jinja2 template asynchronously.
:param filename: The name of the template file to render.
:param context: The context to render the template with.
:return: The rendered template as a string."""

# Set the base directory relative to the cognee root directory
base_directory = get_absolute_path("./infrastructure/llm/prompts")

# Initialize the Jinja2 environment to load templates from the filesystem
env = Environment(
loader = FileSystemLoader(base_directory),
autoescape = select_autoescape(["html", "xml", "txt"])
)

# Load the template by name
template = env.get_template(filename)

# Render the template with the provided context
rendered_template = template.render(context)

return rendered_template

 

요약_콘텐츠: 요약 콘텐츠

You are a summarization engine and you should sumamarize content. Be brief and concise
© 저작권 정책
AiPPT

관련 문서

댓글 없음

댓글에 참여하려면 로그인해야 합니다!
지금 로그인
없음
댓글 없음...