update and refactor demo examples

This commit is contained in:
Milenko Gavric 2026-01-20 13:54:29 +01:00
parent ba94d1270c
commit dab862e058
21 changed files with 793 additions and 407 deletions

View file

@ -0,0 +1,105 @@
"""
Core Features Getting Started Example
Reference: https://colab.research.google.com/drive/12Vi9zID-M3fpKpKiaqDBvkk98ElkRPWy?usp=sharing
"""
import os
import cognee
import asyncio
from cognee.modules.engine.models.node_set import NodeSet
# provide your OpenAI key here
os.environ["LLM_API_KEY"] = ""
# create artifacts directory for storing visualization outputs
artifacts_path = "artifacts"
developer_intro = (
"Hi, I'm an AI/Backend engineer. "
"I build FastAPI services with Pydantic, heavy asyncio/aiohttp pipelines, "
"and production testing via pytest-asyncio. "
"I've shipped low-latency APIs on AWS, Azure, and GoogleCloud."
)
asset_paths = {
"human_agent_conversations": "data/copilot_convesations.json",
"python_zen_principles": "data/zen_principles.md",
"ontology": "data/basic_ontology.owl",
}
human_agent_conversations = asset_paths["human_agent_conversations"]
python_zen_principles = asset_paths["python_zen_principles"]
ontology_path = asset_paths["ontology"]
async def main():
await cognee.prune.prune_data()
await cognee.prune.prune_system(metadata=True)
await cognee.add(developer_intro, node_set=["developer_data"])
await cognee.add(human_agent_conversations, node_set=["developer_data"])
await cognee.add(python_zen_principles, node_set=["principles_data"])
# configure ontology file path for structured data processing
os.environ["ONTOLOGY_FILE_PATH"] = ontology_path
# transform all the data in the cognee store into a knowledge graph backed by embeddings
await cognee.cognify()
# generate the initial graph visualization showing nodesets and ontology structure
initial_graph_visualization_path = (
artifacts_path + "/graph_visualization_nodesets_and_ontology.html"
)
await cognee.visualize_graph(initial_graph_visualization_path)
# enhance the knowledge graph with memory consolidation for improved connections
await cognee.memify()
# generate the second graph visualization after memory enhancement
enhanced_graph_visualization_path = artifacts_path + "/graph_visualization_after_memify.html"
await cognee.visualize_graph(enhanced_graph_visualization_path)
# demonstrate cross-document knowledge retrieval from multiple data sources
results = await cognee.search(
query_text="How does my AsyncWebScraper implementation align with Python's design principles?",
query_type=cognee.SearchType.GRAPH_COMPLETION,
)
print("Python Pattern Analysis:", results)
# demonstrate filtered search using NodeSet to query only specific subsets of memory
results = await cognee.search(
query_text="How should variables be named?",
query_type=cognee.SearchType.GRAPH_COMPLETION,
node_type=NodeSet,
node_name=["principles_data"],
)
print("Filtered search result:", results)
# demonstrate interactive search with feedback mechanism for continuous improvement
answer = await cognee.search(
query_type=cognee.SearchType.GRAPH_COMPLETION,
query_text="What is the most zen thing about Python?",
save_interaction=True,
)
print("Initial answer:", answer)
# provide feedback on the previous search result to improve future retrievals
# the last_k parameter specifies which previous answer to give feedback about
await cognee.search(
query_type=cognee.SearchType.FEEDBACK,
query_text="Last result was useful, I like code that complies with best practices.",
last_k=1,
)
feedback_enhanced_graph_visualization_path = (
artifacts_path + "/graph_visualization_after_feedback.html"
)
await cognee.visualize_graph(feedback_enhanced_graph_visualization_path)
if __name__ == "__main__":
asyncio.run(main())

View file

@ -0,0 +1,290 @@
<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF
xmlns:ns1="http://example.org/ontology#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
>
<rdf:Description rdf:about="http://example.org/ontology#Volkswagen">
<rdfs:comment>Created for making cars accessible to everyone.</rdfs:comment>
<ns1:produces rdf:resource="http://example.org/ontology#VW_Golf"/>
<ns1:produces rdf:resource="http://example.org/ontology#VW_ID4"/>
<ns1:produces rdf:resource="http://example.org/ontology#VW_Touareg"/>
<rdf:type rdf:resource="http://example.org/ontology#CarManufacturer"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#Azure">
<rdf:type rdf:resource="http://example.org/ontology#CloudServiceProvider"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#Porsche">
<ns1:produces rdf:resource="http://example.org/ontology#Porsche_Cayenne"/>
<ns1:produces rdf:resource="http://example.org/ontology#Porsche_Taycan"/>
<ns1:produces rdf:resource="http://example.org/ontology#Porsche_911"/>
<rdf:type rdf:resource="http://example.org/ontology#CarManufacturer"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
<rdfs:comment>Famous for high-performance sports cars.</rdfs:comment>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#Meta">
<rdf:type rdf:resource="http://example.org/ontology#TechnologyCompany"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
<ns1:develops rdf:resource="http://example.org/ontology#Instagram"/>
<ns1:develops rdf:resource="http://example.org/ontology#Facebook"/>
<ns1:develops rdf:resource="http://example.org/ontology#Oculus"/>
<ns1:develops rdf:resource="http://example.org/ontology#WhatsApp"/>
<rdfs:comment>Pioneering social media and virtual reality technology.</rdfs:comment>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#TechnologyCompany">
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Class"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#Apple">
<rdf:type rdf:resource="http://example.org/ontology#TechnologyCompany"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
<rdfs:comment>Known for its innovative consumer electronics and software.</rdfs:comment>
<ns1:develops rdf:resource="http://example.org/ontology#iPad"/>
<ns1:develops rdf:resource="http://example.org/ontology#iPhone"/>
<ns1:develops rdf:resource="http://example.org/ontology#AppleWatch"/>
<ns1:develops rdf:resource="http://example.org/ontology#MacBook"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#Audi">
<ns1:produces rdf:resource="http://example.org/ontology#Audi_eTron"/>
<ns1:produces rdf:resource="http://example.org/ontology#Audi_R8"/>
<ns1:produces rdf:resource="http://example.org/ontology#Audi_A8"/>
<rdf:type rdf:resource="http://example.org/ontology#CarManufacturer"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
<rdfs:comment>Known for its modern designs and technology.</rdfs:comment>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#AmazonEcho">
<rdf:type rdf:resource="http://example.org/ontology#HardwareCompany"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#Porsche_Taycan">
<rdf:type rdf:resource="http://example.org/ontology#ElectricCar"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#BMW">
<ns1:produces rdf:resource="http://example.org/ontology#BMW_7Series"/>
<ns1:produces rdf:resource="http://example.org/ontology#BMW_M4"/>
<ns1:produces rdf:resource="http://example.org/ontology#BMW_iX"/>
<rdf:type rdf:resource="http://example.org/ontology#CarManufacturer"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
<rdfs:comment>Focused on performance and driving pleasure.</rdfs:comment>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#VW_Touareg">
<rdf:type rdf:resource="http://example.org/ontology#SUV"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#SportsCar">
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Class"/>
<rdfs:subClassOf rdf:resource="http://example.org/ontology#Car"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#ElectricCar">
<rdfs:subClassOf rdf:resource="http://example.org/ontology#Car"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Class"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#Google">
<ns1:develops rdf:resource="http://example.org/ontology#GooglePixel"/>
<ns1:develops rdf:resource="http://example.org/ontology#GoogleCloud"/>
<ns1:develops rdf:resource="http://example.org/ontology#Android"/>
<ns1:develops rdf:resource="http://example.org/ontology#GoogleSearch"/>
<rdf:type rdf:resource="http://example.org/ontology#TechnologyCompany"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
<rdfs:comment>Started as a search engine and expanded into cloud computing and AI.</rdfs:comment>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#AmazonPrime">
<rdf:type rdf:resource="http://example.org/ontology#SoftwareCompany"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#Car">
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Class"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#WindowsOS">
<rdf:type rdf:resource="http://example.org/ontology#SoftwareCompany"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#Android">
<rdf:type rdf:resource="http://example.org/ontology#SoftwareCompany"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#Oculus">
<rdf:type rdf:resource="http://example.org/ontology#HardwareCompany"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#GoogleCloud">
<rdf:type rdf:resource="http://example.org/ontology#CloudServiceProvider"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#Microsoft">
<ns1:develops rdf:resource="http://example.org/ontology#Surface"/>
<ns1:develops rdf:resource="http://example.org/ontology#WindowsOS"/>
<ns1:develops rdf:resource="http://example.org/ontology#Azure"/>
<ns1:develops rdf:resource="http://example.org/ontology#Xbox"/>
<rdf:type rdf:resource="http://example.org/ontology#TechnologyCompany"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
<rdfs:comment>Dominant in software, cloud computing, and gaming.</rdfs:comment>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#GoogleSearch">
<rdf:type rdf:resource="http://example.org/ontology#SoftwareCompany"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#Mercedes_SClass">
<rdf:type rdf:resource="http://example.org/ontology#LuxuryCar"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#Audi_A8">
<rdf:type rdf:resource="http://example.org/ontology#LuxuryCar"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#Sedan">
<rdfs:subClassOf rdf:resource="http://example.org/ontology#Car"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Class"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#VW_Golf">
<rdf:type rdf:resource="http://example.org/ontology#Sedan"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#Facebook">
<rdf:type rdf:resource="http://example.org/ontology#SoftwareCompany"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#WhatsApp">
<rdf:type rdf:resource="http://example.org/ontology#SoftwareCompany"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#produces">
<rdfs:domain rdf:resource="http://example.org/ontology#CarManufacturer"/>
<rdfs:range rdf:resource="http://example.org/ontology#Car"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#BMW_7Series">
<rdf:type rdf:resource="http://example.org/ontology#LuxuryCar"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#BMW_M4">
<rdf:type rdf:resource="http://example.org/ontology#SportsCar"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#Audi_eTron">
<rdf:type rdf:resource="http://example.org/ontology#ElectricCar"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#Kindle">
<rdf:type rdf:resource="http://example.org/ontology#HardwareCompany"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#BMW_iX">
<rdf:type rdf:resource="http://example.org/ontology#ElectricCar"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#SoftwareCompany">
<rdfs:subClassOf rdf:resource="http://example.org/ontology#TechnologyCompany"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Class"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#Audi_R8">
<rdf:type rdf:resource="http://example.org/ontology#SportsCar"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#Xbox">
<rdf:type rdf:resource="http://example.org/ontology#HardwareCompany"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#Technology">
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Class"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#Mercedes_EQS">
<rdf:type rdf:resource="http://example.org/ontology#ElectricCar"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#Porsche_911">
<rdf:type rdf:resource="http://example.org/ontology#SportsCar"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#HardwareCompany">
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Class"/>
<rdfs:subClassOf rdf:resource="http://example.org/ontology#TechnologyCompany"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#MercedesBenz">
<ns1:produces rdf:resource="http://example.org/ontology#Mercedes_SClass"/>
<ns1:produces rdf:resource="http://example.org/ontology#Mercedes_EQS"/>
<ns1:produces rdf:resource="http://example.org/ontology#Mercedes_AMG_GT"/>
<rdfs:comment>Synonymous with luxury and quality.</rdfs:comment>
<rdf:type rdf:resource="http://example.org/ontology#CarManufacturer"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#Amazon">
<rdf:type rdf:resource="http://example.org/ontology#TechnologyCompany"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
<ns1:develops rdf:resource="http://example.org/ontology#Kindle"/>
<ns1:develops rdf:resource="http://example.org/ontology#AmazonEcho"/>
<ns1:develops rdf:resource="http://example.org/ontology#AWS"/>
<ns1:develops rdf:resource="http://example.org/ontology#AmazonPrime"/>
<rdfs:comment>From e-commerce to cloud computing giant with AWS.</rdfs:comment>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#Instagram">
<rdf:type rdf:resource="http://example.org/ontology#SoftwareCompany"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#AWS">
<rdf:type rdf:resource="http://example.org/ontology#CloudServiceProvider"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#SUV">
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Class"/>
<rdfs:subClassOf rdf:resource="http://example.org/ontology#Car"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#VW_ID4">
<rdf:type rdf:resource="http://example.org/ontology#ElectricCar"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#CloudServiceProvider">
<rdfs:subClassOf rdf:resource="http://example.org/ontology#TechnologyCompany"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Class"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#Surface">
<rdf:type rdf:resource="http://example.org/ontology#HardwareCompany"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#iPad">
<rdf:type rdf:resource="http://example.org/ontology#HardwareCompany"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#iPhone">
<rdf:type rdf:resource="http://example.org/ontology#HardwareCompany"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#Mercedes_AMG_GT">
<rdf:type rdf:resource="http://example.org/ontology#SportsCar"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#MacBook">
<rdf:type rdf:resource="http://example.org/ontology#HardwareCompany"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#develops">
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/>
<rdfs:range rdf:resource="http://example.org/ontology#Technology"/>
<rdfs:domain rdf:resource="http://example.org/ontology#TechnologyCompany"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#LuxuryCar">
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Class"/>
<rdfs:subClassOf rdf:resource="http://example.org/ontology#Car"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#AppleWatch">
<rdf:type rdf:resource="http://example.org/ontology#HardwareCompany"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#Porsche_Cayenne">
<rdf:type rdf:resource="http://example.org/ontology#SUV"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#GooglePixel">
<rdf:type rdf:resource="http://example.org/ontology#HardwareCompany"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#Company">
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Class"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.org/ontology#CarManufacturer">
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Class"/>
<rdfs:subClassOf rdf:resource="http://example.org/ontology#Company"/>
</rdf:Description>
</rdf:RDF>

View file

@ -0,0 +1,107 @@
{
"conversations": [
{
"id": "conv_001",
"timestamp": "2024-01-15T10:30:00Z",
"topic": "async/await patterns",
"user_query": "I'm building a web scraper that needs to handle thousands of URLs concurrently. What's the best way to structure this with asyncio?",
"assistant_response": "For high-concurrency web scraping, you'll want to use asyncio with aiohttp and implement proper semaphore-based rate limiting. Here's a robust pattern:\n\n```python\nimport asyncio\nimport aiohttp\nfrom typing import List, Dict, Any\n\nclass AsyncWebScraper:\n def __init__(self, max_concurrent: int = 100):\n self.semaphore = asyncio.Semaphore(max_concurrent)\n self.session = None\n \n async def __aenter__(self):\n self.session = aiohttp.ClientSession(\n timeout=aiohttp.ClientTimeout(total=30),\n connector=aiohttp.TCPConnector(limit=100)\n )\n return self\n \n async def __aexit__(self, exc_type, exc_val, exc_tb):\n if self.session:\n await self.session.close()\n \n async def fetch_url(self, url: str) -> Dict[str, Any]:\n async with self.semaphore:\n try:\n async with self.session.get(url) as response:\n content = await response.text()\n return {\n 'url': url,\n 'status': response.status,\n 'content': content,\n 'headers': dict(response.headers)\n }\n except Exception as e:\n return {'url': url, 'error': str(e)}\n \n async def scrape_urls(self, urls: List[str]) -> List[Dict[str, Any]]:\n tasks = [self.fetch_url(url) for url in urls]\n return await asyncio.gather(*tasks, return_exceptions=True)\n\n# Usage\nasync def main():\n urls = ['http://example.com'] * 1000 # Your URLs here\n \n async with AsyncWebScraper(max_concurrent=50) as scraper:\n results = await scraper.scrape_urls(urls)\n \n successful = [r for r in results if 'error' not in r]\n print(f'Successfully scraped {len(successful)} URLs')\n\nif __name__ == '__main__':\n asyncio.run(main())\n```\n\nKey points:\n- Semaphore controls concurrency to avoid overwhelming servers\n- Context manager ensures proper cleanup\n- TCPConnector with connection pooling\n- Proper exception handling for failed requests",
"code_context": {
"file": "scraper.py",
"language": "python",
"patterns_discussed": ["async/await", "context_managers", "semaphores", "aiohttp", "error_handling"]
},
"follow_up_questions": [
"How do I add retry logic for failed requests?",
"What's the best way to parse the scraped HTML content?"
]
},
{
"id": "conv_002",
"timestamp": "2024-01-16T14:20:00Z",
"topic": "dataclass vs pydantic",
"user_query": "When should I use dataclasses vs Pydantic models? I'm building an API and need to handle user input validation.",
"assistant_response": "Great question! For API development with input validation, here's when to use each:\n\n**Use Pydantic when:**\n- Building APIs (FastAPI, Django REST)\n- Need runtime validation of external data\n- Want automatic JSON serialization/deserialization\n- Need complex validation rules\n- Working with configuration files\n\n**Use dataclasses when:**\n- Internal data structures\n- Simple data containers\n- Want to stay in stdlib\n- Performance is critical (dataclasses are faster)\n\nFor your API, I'd recommend Pydantic:\n\n```python\nfrom pydantic import BaseModel, validator, Field\nfrom typing import Optional, List\nfrom datetime import datetime\nfrom enum import Enum\n\nclass UserRole(str, Enum):\n ADMIN = 'admin'\n USER = 'user'\n GUEST = 'guest'\n\nclass CreateUserRequest(BaseModel):\n username: str = Field(..., min_length=3, max_length=50, regex=r'^[a-zA-Z0-9_]+$')\n email: str = Field(..., regex=r'^[\\w\\.-]+@[\\w\\.-]+\\.\\w+$')\n password: str = Field(..., min_length=8)\n role: UserRole = UserRole.USER\n tags: Optional[List[str]] = None\n \n @validator('password')\n def validate_password(cls, v):\n if not any(c.isupper() for c in v):\n raise ValueError('Password must contain uppercase letter')\n if not any(c.isdigit() for c in v):\n raise ValueError('Password must contain digit')\n return v\n \n @validator('tags')\n def validate_tags(cls, v):\n if v and len(v) > 10:\n raise ValueError('Too many tags')\n return v\n\nclass User(BaseModel):\n id: int\n username: str\n email: str\n role: UserRole\n created_at: datetime\n is_active: bool = True\n \n class Config:\n orm_mode = True\n json_encoders = { datetime: lambda v: v.isoformat() }\n\n# FastAPI usage\nfrom fastapi import FastAPI, HTTPException\n\napp = FastAPI()\n\n@app.post('/users/', response_model=User)\nasync def create_user(user_data: CreateUserRequest):\n try:\n new_user = await create_user_in_db(user_data)\n return User.from_orm(new_user)\n except Exception as e:\n raise HTTPException(status_code=400, detail=str(e))\n```\n\nPydantic gives you:\n- Automatic request validation\n- Clear error messages\n- Type coercion\n- JSON Schema generation\n- IDE support with type hints",
"code_context": {
"file": "models.py",
"language": "python",
"patterns_discussed": ["pydantic", "dataclasses", "validation", "fastapi", "type_hints", "enums"]
},
"follow_up_questions": [
"How do I handle nested validation with Pydantic?",
"Can I use Pydantic with SQLAlchemy models?"
]
},
{
"id": "conv_003",
"timestamp": "2024-01-17T09:15:00Z",
"topic": "testing patterns",
"user_query": "I'm struggling with testing async code and database interactions. What's the best approach for pytest with async functions?",
"assistant_response": "Testing async code can be tricky! Here's a comprehensive approach using pytest-asyncio and proper test isolation...",
"code_context": {
"file": "test_users.py",
"language": "python",
"patterns_discussed": ["pytest", "async_testing", "fixtures", "mocking", "database_testing", "fastapi_testing"]
},
"follow_up_questions": [
"How do I test WebSocket connections?",
"What's the best way to test database migrations?"
]
},
{
"id": "conv_004",
"timestamp": "2024-01-18T16:45:00Z",
"topic": "performance optimization",
"user_query": "My FastAPI app is getting slow with large datasets. How can I optimize database queries and response times?",
"assistant_response": "Performance optimization in FastAPI apps typically involves several layers...",
"code_context": {
"file": "optimizations.py",
"language": "python",
"patterns_discussed": ["performance_optimization", "caching", "database_optimization", "async_patterns", "monitoring"]
},
"follow_up_questions": [
"How do I implement database connection pooling properly?",
"What's the best way to handle memory usage with large datasets?"
]
},
{
"id": "conv_005",
"timestamp": "2024-01-19T11:30:00Z",
"topic": "error handling and logging",
"user_query": "I need to implement proper error handling and logging across my Python application. What's the best approach for production-ready error management?",
"assistant_response": "Excellent question! Proper error handling and logging are crucial for production applications...",
"code_context": {
"file": "error_handling.py",
"language": "python",
"patterns_discussed": ["error_handling", "logging", "exceptions", "middleware", "decorators", "fastapi"]
},
"follow_up_questions": [
"How do I integrate this with external monitoring tools like Sentry?",
"What's the best way to handle errors in background tasks?"
]
}
],
"metadata": {
"total_conversations": 5,
"date_range": "2024-01-15 to 2024-01-19",
"topics_covered": [
"async/await patterns",
"dataclass vs pydantic",
"testing patterns",
"performance optimization",
"error handling and logging"
],
"code_patterns_discussed": [
"asyncio", "aiohttp", "semaphores", "context_managers",
"pydantic", "fastapi", "type_hints", "validation",
"pytest", "async_testing", "fixtures", "mocking",
"performance_optimization", "caching", "database_optimization",
"error_handling", "logging", "exceptions", "middleware"
],
"difficulty_levels": {
"beginner": 1,
"intermediate": 2,
"advanced": 2
}
}
}

View file

@ -0,0 +1,74 @@
# The Zen of Python: Practical Guide
## Overview
The Zen of Python (Tim Peters, import this) captures Python's philosophy. Use these principles as a checklist during design, coding, and reviews.
## Key Principles With Guidance
### 1. Beautiful is better than ugly
Prefer descriptive names, clear structure, and consistent formatting.
### 2. Explicit is better than implicit
Be clear about behavior, imports, and types.
```python
from datetime import datetime, timedelta
def get_future_date(days_ahead: int) -> datetime:
return datetime.now() + timedelta(days=days_ahead)
```
### 3. Simple is better than complex
Choose straightforward solutions first.
### 4. Complex is better than complicated
When complexity is needed, organize it with clear abstractions.
### 5. Flat is better than nested
Use early returns to reduce indentation.
### 6. Sparse is better than dense
Give code room to breathe with whitespace.
### 7. Readability counts
Optimize for human readers; add docstrings for nontrivial code.
### 8. Special cases aren't special enough to break the rules
Stay consistent; exceptions should be rare and justified.
### 9. Although practicality beats purity
Prefer practical solutions that teams can maintain.
### 10. Errors should never pass silently
Handle exceptions explicitly; log with context.
### 11. Unless explicitly silenced
Silence only specific, acceptable errors and document why.
### 12. In the face of ambiguity, refuse the temptation to guess
Require explicit inputs and behavior.
### 13. There should be one obvious way to do it
Prefer standard library patterns and idioms.
### 14. Although that way may not be obvious at first
Learn Python idioms; embrace clarity over novelty.
### 15. Now is better than never; 16. Never is often better than right now
Iterate, but don't rush broken code.
### 17/18. Hard to explain is bad; easy to explain is good
Prefer designs you can explain simply.
### 19. Namespaces are one honking great idea
Use modules/packages to separate concerns; avoid wildcard imports.
## Modern Python Tie-ins
- Type hints reinforce explicitness
- Context managers enforce safe resource handling
- Dataclasses improve readability for data containers
## Quick Review Checklist
- Is it readable and explicit?
- Is this the simplest working solution?
- Are errors explicit and logged?
- Are modules/namespaces used appropriately?

View file

@ -1,6 +0,0 @@
"""
Core Features Getting Started Example
Reference: https://colab.research.google.com/drive/12Vi9zID-M3fpKpKiaqDBvkk98ElkRPWy?usp=sharing
"""

View file

@ -6,7 +6,29 @@ from cognee import config, add, cognify, search, SearchType, prune, visualize_gr
from cognee.low_level import DataPoint
async def main():
# Define a custom graph model for programming languages.
class FieldType(DataPoint):
name: str = "Field"
class Field(DataPoint):
name: str
is_type: FieldType
metadata: dict = {"index_fields": ["name"]}
class ProgrammingLanguageType(DataPoint):
name: str = "Programming Language"
class ProgrammingLanguage(DataPoint):
name: str
used_in: list[Field] = []
is_type: ProgrammingLanguageType
metadata: dict = {"index_fields": ["name"]}
def set_up_config():
data_directory_path = str(
pathlib.Path(os.path.join(pathlib.Path(__file__).parent, ".data_storage")).resolve()
)
@ -19,37 +41,8 @@ async def main():
# Set up the Cognee system directory. Cognee will store system files and databases here.
config.system_root_directory(cognee_directory_path)
# Prune data and system metadata before running, only if we want "fresh" state.
await prune.prune_data()
await prune.prune_system(metadata=True)
text = "The Python programming language is widely used in data analysis, web development, and machine learning."
# Add the text data to Cognee.
await add(text)
# Define a custom graph model for programming languages.
class FieldType(DataPoint):
name: str = "Field"
class Field(DataPoint):
name: str
is_type: FieldType
metadata: dict = {"index_fields": ["name"]}
class ProgrammingLanguageType(DataPoint):
name: str = "Programming Language"
class ProgrammingLanguage(DataPoint):
name: str
used_in: list[Field] = []
is_type: ProgrammingLanguageType
metadata: dict = {"index_fields": ["name"]}
# Cognify the text data.
await cognify(graph_model=ProgrammingLanguage)
# Or use our simple graph preview
async def visualize_data():
graph_file_path = str(
pathlib.Path(
os.path.join(pathlib.Path(__file__).parent, ".artifacts/graph_visualization.html")
@ -57,28 +50,39 @@ async def main():
)
await visualize_graph(graph_file_path)
async def main():
set_up_config()
# Prune data and system metadata before running, only if we want "fresh" state.
await prune.prune_data()
await prune.prune_system(metadata=True)
text = "The Python programming language is widely used in data analysis, web development, and machine learning."
await add(text)
await cognify(graph_model=ProgrammingLanguage)
await visualize_data()
# Completion query that uses graph data to form context.
graph_completion = await search(
query_text="What is python?", query_type=SearchType.GRAPH_COMPLETION
query_text="What is Python?", query_type=SearchType.GRAPH_COMPLETION
)
print("Graph completion result is:")
print(graph_completion)
# Completion query that uses document chunks to form context.
rag_completion = await search(
query_text="What is Python?", query_type=SearchType.RAG_COMPLETION
)
print("Completion result is:")
print(rag_completion)
# Query all summaries related to query.
summaries = await search(query_text="Python", query_type=SearchType.SUMMARIES)
print("Summary results are:")
for summary in summaries:
print(summary)
chunks = await search(query_text="Python", query_type=SearchType.CHUNKS)
print("Chunk results are:")
for chunk in chunks:
print(chunk)

View file

@ -1,7 +0,0 @@
"""
Custom Prompt Example
Reference: https://docs.cognee.ai/guides/custom-prompts
"""

View file

@ -1,4 +0,0 @@
"""
Direct LLM Call for Structured Output Example
Reference: https://docs.cognee.ai/guides/low-level-llm
"""

View file

@ -1,5 +0,0 @@
"""
Graph Visualization Example
Reference: https://docs.cognee.ai/guides/graph-visualization
"""

View file

@ -0,0 +1,16 @@
1. Audi
Audi is known for its modern designs and advanced technology. Founded in the early 1900s, the brand has earned a reputation for precision engineering and innovation. With features like the Quattro all-wheel-drive system, Audi offers a range of vehicles from stylish sedans to high-performance sports cars.
2. BMW
BMW, short for Bayerische Motoren Werke, is celebrated for its focus on performance and driving pleasure. The company's vehicles are designed to provide a dynamic and engaging driving experience, and their slogan, "The Ultimate Driving Machine," reflects that commitment. BMW produces a variety of cars that combine luxury with sporty performance.
3. Mercedes-Benz
Mercedes-Benz is synonymous with luxury and quality. With a history dating back to the early 20th century, the brand is known for its elegant designs, innovative safety features, and high-quality engineering. Mercedes-Benz manufactures not only luxury sedans but also SUVs, sports cars, and commercial vehicles, catering to a wide range of needs.
4. Porsche
Porsche is a name that stands for high-performance sports cars. Founded in 1931, the brand has become famous for models like the iconic Porsche 911. Porsche cars are celebrated for their speed, precision, and distinctive design, appealing to car enthusiasts who value both performance and style.
5. Volkswagen
Volkswagen, which means "people's car" in German, was established with the idea of making affordable and reliable vehicles accessible to everyone. Over the years, Volkswagen has produced several iconic models, such as the Beetle and the Golf. Today, it remains one of the largest car manufacturers in the world, offering a wide range of vehicles that balance practicality with quality.
Each of these car manufacturer contributes to Germany's reputation as a leader in the global automotive industry, showcasing a blend of innovation, performance, and design excellence.

View file

@ -0,0 +1,16 @@
1. Apple
Apple is renowned for its innovative consumer electronics and software. Its product lineup includes the iPhone, iPad, Mac computers, and wearables like the Apple Watch. Known for its emphasis on sleek design and user-friendly interfaces, Apple has built a loyal customer base and created a seamless ecosystem that integrates hardware, software, and services.
2. Google
Founded in 1998, Google started as a search engine and quickly became the go-to resource for finding information online. Over the years, the company has diversified its offerings to include digital advertising, cloud computing, mobile operating systems (Android), and various web services like Gmail and Google Maps. Google's innovations have played a major role in shaping the internet landscape.
3. Microsoft
Microsoft Corporation has been a dominant force in software for decades. Its Windows operating system and Microsoft Office suite are staples in both business and personal computing. In recent years, Microsoft has expanded into cloud computing with Azure, gaming with the Xbox platform, and even hardware through products like the Surface line. This evolution has helped the company maintain its relevance in a rapidly changing tech world.
4. Amazon
What began as an online bookstore has grown into one of the largest e-commerce platforms globally. Amazon is known for its vast online marketplace, but its influence extends far beyond retail. With Amazon Web Services (AWS), the company has become a leader in cloud computing, offering robust solutions that power websites, applications, and businesses around the world. Amazon's constant drive for innovation continues to reshape both retail and technology sectors.
5. Meta
Meta, originally known as Facebook, revolutionized social media by connecting billions of people worldwide. Beyond its core social networking service, Meta is investing in the next generation of digital experiences through virtual and augmented reality technologies, with projects like Oculus. The company's efforts signal a commitment to evolving digital interaction and building the metaverse—a shared virtual space where users can connect and collaborate.
Each of these companies has significantly impacted the technology landscape, driving innovation and transforming everyday life through their groundbreaking products and services.

View file

@ -8,43 +8,11 @@ from cognee.shared.logging_utils import setup_logging
from cognee.modules.ontology.rdf_xml.RDFLibOntologyResolver import RDFLibOntologyResolver
from cognee.modules.ontology.ontology_config import Config
text_1 = """
1. Audi
Audi is known for its modern designs and advanced technology. Founded in the early 1900s, the brand has earned a reputation for precision engineering and innovation. With features like the Quattro all-wheel-drive system, Audi offers a range of vehicles from stylish sedans to high-performance sports cars.
with open("data/text_1.txt", "r", encoding="utf-8") as f:
text_1 = f.read()
2. BMW
BMW, short for Bayerische Motoren Werke, is celebrated for its focus on performance and driving pleasure. The company's vehicles are designed to provide a dynamic and engaging driving experience, and their slogan, "The Ultimate Driving Machine," reflects that commitment. BMW produces a variety of cars that combine luxury with sporty performance.
3. Mercedes-Benz
Mercedes-Benz is synonymous with luxury and quality. With a history dating back to the early 20th century, the brand is known for its elegant designs, innovative safety features, and high-quality engineering. Mercedes-Benz manufactures not only luxury sedans but also SUVs, sports cars, and commercial vehicles, catering to a wide range of needs.
4. Porsche
Porsche is a name that stands for high-performance sports cars. Founded in 1931, the brand has become famous for models like the iconic Porsche 911. Porsche cars are celebrated for their speed, precision, and distinctive design, appealing to car enthusiasts who value both performance and style.
5. Volkswagen
Volkswagen, which means "people's car" in German, was established with the idea of making affordable and reliable vehicles accessible to everyone. Over the years, Volkswagen has produced several iconic models, such as the Beetle and the Golf. Today, it remains one of the largest car manufacturers in the world, offering a wide range of vehicles that balance practicality with quality.
Each of these car manufacturer contributes to Germany's reputation as a leader in the global automotive industry, showcasing a blend of innovation, performance, and design excellence.
"""
text_2 = """
1. Apple
Apple is renowned for its innovative consumer electronics and software. Its product lineup includes the iPhone, iPad, Mac computers, and wearables like the Apple Watch. Known for its emphasis on sleek design and user-friendly interfaces, Apple has built a loyal customer base and created a seamless ecosystem that integrates hardware, software, and services.
2. Google
Founded in 1998, Google started as a search engine and quickly became the go-to resource for finding information online. Over the years, the company has diversified its offerings to include digital advertising, cloud computing, mobile operating systems (Android), and various web services like Gmail and Google Maps. Google's innovations have played a major role in shaping the internet landscape.
3. Microsoft
Microsoft Corporation has been a dominant force in software for decades. Its Windows operating system and Microsoft Office suite are staples in both business and personal computing. In recent years, Microsoft has expanded into cloud computing with Azure, gaming with the Xbox platform, and even hardware through products like the Surface line. This evolution has helped the company maintain its relevance in a rapidly changing tech world.
4. Amazon
What began as an online bookstore has grown into one of the largest e-commerce platforms globally. Amazon is known for its vast online marketplace, but its influence extends far beyond retail. With Amazon Web Services (AWS), the company has become a leader in cloud computing, offering robust solutions that power websites, applications, and businesses around the world. Amazon's constant drive for innovation continues to reshape both retail and technology sectors.
5. Meta
Meta, originally known as Facebook, revolutionized social media by connecting billions of people worldwide. Beyond its core social networking service, Meta is investing in the next generation of digital experiences through virtual and augmented reality technologies, with projects like Oculus. The company's efforts signal a commitment to evolving digital interaction and building the metaverse—a shared virtual space where users can connect and collaborate.
Each of these companies has significantly impacted the technology landscape, driving innovation and transforming everyday life through their groundbreaking products and services.
"""
with open("data/text_2.txt", "r", encoding="utf-8") as f:
text_2 = f.read()
async def main():

View file

@ -1,5 +0,0 @@
"""
Retrievers and Search Examples
Reference: https://docs.cognee.ai/guides/search-basics
"""

View file

@ -0,0 +1,41 @@
import asyncio
import cognee
from cognee.shared.logging_utils import setup_logging, ERROR
from cognee.api.v1.search import SearchType
# Prerequisites:
# 1. Copy `.env.template` and rename it to `.env`.
# 2. Add your OpenAI API key to the `.env` file in the `LLM_API_KEY` field:
# LLM_API_KEY = "your_key_here"
async def main():
# Prune data/system, add conversation, cognify.
await cognee.prune.prune_data()
await cognee.prune.prune_system(metadata=True)
text = """
Natural language processing (NLP) is an interdisciplinary
subfield of computer science and information retrieval.
"""
await cognee.add(text)
await cognee.cognify()
query_text = "Tell me about NLP"
print(f"Searching cognee for insights with query: '{query_text}'")
# Query cognee for insights on the added text
search_results = await cognee.search(
query_type=SearchType.GRAPH_COMPLETION, query_text=query_text
)
for result_text in search_results:
print(result_text)
if __name__ == "__main__":
logger = setup_logging(log_level=ERROR)
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
loop.run_until_complete(main())
finally:
loop.run_until_complete(loop.shutdown_asyncgens())

View file

@ -1,70 +0,0 @@
import asyncio
import cognee
from cognee.shared.logging_utils import setup_logging, ERROR
from cognee.api.v1.search import SearchType
# Prerequisites:
# 1. Copy `.env.template` and rename it to `.env`.
# 2. Add your OpenAI API key to the `.env` file in the `LLM_API_KEY` field:
# LLM_API_KEY = "your_key_here"
async def main():
# Create a clean slate for cognee -- reset data and system state
print("Resetting cognee data...")
await cognee.prune.prune_data()
await cognee.prune.prune_system(metadata=True)
print("Data reset complete.\n")
# cognee knowledge graph will be created based on this text
text = """
Natural language processing (NLP) is an interdisciplinary
subfield of computer science and information retrieval.
"""
print("Adding text to cognee:")
print(text.strip())
# Add the text, and make it available for cognify
await cognee.add(text)
print("Text added successfully.\n")
print("Running cognify to create knowledge graph...\n")
print("Cognify process steps:")
print("1. Classifying the document: Determining the type and category of the input text.")
print(
"2. Checking permissions: Ensuring the user has the necessary rights to process the text."
)
print(
"3. Extracting text chunks: Breaking down the text into sentences or phrases for analysis."
)
print("4. Adding data points: Storing the extracted chunks for processing.")
print(
"5. Generating knowledge graph: Extracting entities and relationships to form a knowledge graph."
)
print("6. Summarizing text: Creating concise summaries of the content for quick insights.\n")
# Use LLMs and cognee to create knowledge graph
await cognee.cognify()
print("Cognify process complete.\n")
query_text = "Tell me about NLP"
print(f"Searching cognee for insights with query: '{query_text}'")
# Query cognee for insights on the added text
search_results = await cognee.search(
query_type=SearchType.GRAPH_COMPLETION, query_text=query_text
)
print("Search results:")
# Display results
for result_text in search_results:
print(result_text)
if __name__ == "__main__":
logger = setup_logging(log_level=ERROR)
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
loop.run_until_complete(main())
finally:
loop.run_until_complete(loop.shutdown_asyncgens())

View file

@ -1,101 +0,0 @@
import asyncio
import cognee
from cognee.shared.logging_utils import setup_logging, INFO
from cognee.api.v1.search import SearchType
biography_1 = """
Attaphol Buspakom Attaphol Buspakom ( ; ) , nicknamed Tak ( ; ) ; 1 October 1962 16 April 2015 ) was a Thai national and football coach . He was given the role at Muangthong United and Buriram United after TTM Samut Sakhon folded after the 2009 season . He played for the Thailand national football team , appearing in several FIFA World Cup qualifying matches .
Club career .
Attaphol began his career as a player at Thai Port FC Authority of Thailand in 1985 . In his first year , he won his first championship with the club . He played for the club until 1989 and in 1987 also won the Queens Cup . He then moved to Malaysia for two seasons for Pahang FA , then return to Thailand to his former club . His time from 1991 to 1994 was marked by less success than in his first stay at Port Authority . From 1994 to 1996 he played for Pahang again and this time he was able to win with the club , the Malaysia Super League and also reached the final of the Malaysia Cup and the Malaysia FA Cup . Both cup finals but lost . Back in Thailand , he let end his playing career at FC Stock Exchange of Thailand , with which he once again runner-up in 1996-97 . In 1998 , he finished his career .
International career .
For the Thailand national football team Attaphol played between 1985 and 1998 a total of 85 games and scored 13 results . In 1992 , he participated with the team in the finals of the Asian Cup . He also stood in various cadres to qualifications to FIFA World Cup .
Coaching career .
Bec Tero Sasana .
In BEC Tero Sasana F.C . began his coaching career in 2001 for him , first as assistant coach . He took over the reigning champions of the Thai League T1 , after his predecessor Pichai Pituwong resigned from his post . It was his first coach station and he had the difficult task of leading the club through the new AFC Champions League . He could accomplish this task with flying colors and even led the club to the finals . The finale , then still played in home and away matches , was lost with 1:2 at the end against Al Ain FC . Attaphol is and was next to Charnwit Polcheewin the only coach who managed a club from Thailand to lead to the final of the AFC Champions League . 2002-03 and 2003-04 he won with the club also two runner-up . In his team , which reached the final of the Champions League , were a number of exceptional players like Therdsak Chaiman , Worrawoot Srimaka , Dusit Chalermsan and Anurak Srikerd .
Geylang United / Krung Thai Bank .
In 2006 , he went to Singapore in the S-League to Geylang United He was released after a few months due to lack of success . In 2008 , he took over as coach at Krung Thai Bank F.C. , where he had almost a similar task , as a few years earlier by BEC-Tero . As vice-champion of the club was also qualified for the AFC Champions League . However , he failed to lead the team through the group stage of the season 2008 and beyond . With the Kashima Antlers of Japan and Beijing Guoan F.C . athletic competition was too great . One of the highlights was put under his leadership , yet the club . In the group match against the Vietnam club Nam Dinh F.C . his team won with 9-1 , but also lost four weeks later with 1-8 against Kashima Antlers . At the end of the National Football League season , he reached the Krung Thai 6th Table space . The Erstligalizenz the club was sold at the end of the season at the Bangkok Glass F.C. . Attaphol finished his coaching career with the club and accepted an offer of TTM Samutsakorn . After only a short time in office
Muangthong United .
In 2009 , he received an offer from Muangthong United F.C. , which he accepted and changed . He can champion Muang Thong United for 2009 Thai Premier League and Attaphol won Coach of The year for Thai Premier League and he was able to lead Muang Thong United to play AFC Champions League qualifying play-off for the first in the clubs history .
Buriram United .
In 2010 Buspakom moved from Muangthong United to Buriram United F.C. . He received Coach of the Month in Thai Premier League 2 time in June and October . In 2011 , he led Buriram United win 2011 Thai Premier League second time for club and set a record with the most points in the Thai League T1 for 85 point and He led Buriram win 2011 Thai FA Cup by beat Muangthong United F.C . 1-0 and he led Buriram win 2011 Thai League Cup by beat Thai Port F.C . 2-0 . In 2012 , he led Buriram United to the 2012 AFC Champions League group stage . Buriram along with Guangzhou Evergrande F.C . from China , Kashiwa Reysol from Japan and Jeonbuk Hyundai Motors which are all champions from their country . In the first match of Buriram they beat Kashiwa 3-2 and Second Match they beat Guangzhou 1-2 at the Tianhe Stadium . Before losing to Jeonbuk 0-2 and 3-2 with lose Kashiwa and Guangzhou 1-0 and 1-2 respectively and Thai Premier League Attaphol lead Buriram end 4th for table with win 2012 Thai FA Cup and 2012 Thai League Cup .
Bangkok Glass .
In 2013 , he moved from Buriram United to Bangkok Glass F.C. .
Individual
- Thai Premier League Coach of the Year ( 3 ) : 2001-02 , 2009 , 2013
"""
biography_2 = """
Arnulf Øverland Ole Peter Arnulf Øverland ( 27 April 1889 25 March 1968 ) was a Norwegian poet and artist . He is principally known for his poetry which served to inspire the Norwegian resistance movement during the German occupation of Norway during World War II .
Biography .
Øverland was born in Kristiansund and raised in Bergen . His parents were Peter Anton Øverland ( 18521906 ) and Hanna Hage ( 18541939 ) . The early death of his father , left the family economically stressed . He was able to attend Bergen Cathedral School and in 1904 Kristiania Cathedral School . He graduated in 1907 and for a time studied philology at University of Kristiania . Øverland published his first collection of poems ( 1911 ) .
Øverland became a communist sympathizer from the early 1920s and became a member of Mot Dag . He also served as chairman of the Norwegian Students Society 192328 . He changed his stand in 1937 , partly as an expression of dissent against the ongoing Moscow Trials . He was an avid opponent of Nazism and in 1936 he wrote the poem Du ikke sove which was printed in the journal Samtiden . It ends with . ( I thought: : Something is imminent . Our era is over Europes on fire! ) . Probably the most famous line of the poem is ( You mustnt endure so well the injustice that doesnt affect you yourself! )
During the German occupation of Norway from 1940 in World War II , he wrote to inspire the Norwegian resistance movement . He wrote a series of poems which were clandestinely distributed , leading to the arrest of both him and his future wife Margrete Aamot Øverland in 1941 . Arnulf Øverland was held first in the prison camp of Grini before being transferred to Sachsenhausen concentration camp in Germany . He spent a four-year imprisonment until the liberation of Norway in 1945 . His poems were later collected in Vi overlever alt and published in 1945 .
Øverland played an important role in the Norwegian language struggle in the post-war era . He became a noted supporter for the conservative written form of Norwegian called Riksmål , he was president of Riksmålsforbundet ( an organization in support of Riksmål ) from 1947 to 1956 . In addition , Øverland adhered to the traditionalist style of writing , criticising modernist poetry on several occasions . His speech Tungetale fra parnasset , published in Arbeiderbladet in 1954 , initiated the so-called Glossolalia debate .
Personal life .
In 1918 he had married the singer Hildur Arntzen ( 18881957 ) . Their marriage was dissolved in 1939 . In 1940 , he married Bartholine Eufemia Leganger ( 19031995 ) . They separated shortly after , and were officially divorced in 1945 . Øverland was married to journalist Margrete Aamot Øverland ( 19131978 ) during June 1945 . In 1946 , the Norwegian Parliament arranged for Arnulf and Margrete Aamot Øverland to reside at the Grotten . He lived there until his death in 1968 and she lived there for another ten years until her death in 1978 . Arnulf Øverland was buried at Vår Frelsers Gravlund in Oslo . Joseph Grimeland designed the bust of Arnulf Øverland ( bronze , 1970 ) at his grave site .
Selected Works .
- Den ensomme fest ( 1911 )
- Berget det blå ( 1927 )
- En Hustavle ( 1929 )
- Den røde front ( 1937 )
- Vi overlever alt ( 1945 )
- Sverdet bak døren ( 1956 )
- Livets minutter ( 1965 )
Awards .
- Gyldendals Endowment ( 1935 )
- Dobloug Prize ( 1951 )
- Mads Wiel Nygaards legat ( 1961 )
"""
async def main():
await cognee.prune.prune_data()
await cognee.prune.prune_system(metadata=True)
await cognee.add([biography_1, biography_2])
await cognee.cognify(temporal_cognify=True)
queries = [
"What happened before 1980?",
"What happened after 2010?",
"What happened between 2000 and 2006?",
"What happened between 1903 and 1995, I am interested in the Selected Works of Arnulf Øverland Ole Peter Arnulf Øverland?",
"Who is Attaphol Buspakom Attaphol Buspakom?",
"Who was Arnulf Øverland?",
]
for query_text in queries:
search_results = await cognee.search(
query_type=SearchType.TEMPORAL,
query_text=query_text,
top_k=15,
)
print(f"Query: {query_text}")
print(f"Results: {search_results}\n")
if __name__ == "__main__":
logger = setup_logging(log_level=INFO)
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
loop.run_until_complete(main())
finally:
loop.run_until_complete(loop.shutdown_asyncgens())

View file

@ -0,0 +1,26 @@
Attaphol Buspakom Attaphol Buspakom ( ; ) , nicknamed Tak ( ; ) ; 1 October 1962 16 April 2015 ) was a Thai national and football coach . He was given the role at Muangthong United and Buriram United after TTM Samut Sakhon folded after the 2009 season . He played for the Thailand national football team , appearing in several FIFA World Cup qualifying matches .
Club career .
Attaphol began his career as a player at Thai Port FC Authority of Thailand in 1985 . In his first year , he won his first championship with the club . He played for the club until 1989 and in 1987 also won the Queens Cup . He then moved to Malaysia for two seasons for Pahang FA , then return to Thailand to his former club . His time from 1991 to 1994 was marked by less success than in his first stay at Port Authority . From 1994 to 1996 he played for Pahang again and this time he was able to win with the club , the Malaysia Super League and also reached the final of the Malaysia Cup and the Malaysia FA Cup . Both cup finals but lost . Back in Thailand , he let end his playing career at FC Stock Exchange of Thailand , with which he once again runner-up in 1996-97 . In 1998 , he finished his career .
International career .
For the Thailand national football team Attaphol played between 1985 and 1998 a total of 85 games and scored 13 results . In 1992 , he participated with the team in the finals of the Asian Cup . He also stood in various cadres to qualifications to FIFA World Cup .
Coaching career .
Bec Tero Sasana .
In BEC Tero Sasana F.C . began his coaching career in 2001 for him , first as assistant coach . He took over the reigning champions of the Thai League T1 , after his predecessor Pichai Pituwong resigned from his post . It was his first coach station and he had the difficult task of leading the club through the new AFC Champions League . He could accomplish this task with flying colors and even led the club to the finals . The finale , then still played in home and away matches , was lost with 1:2 at the end against Al Ain FC . Attaphol is and was next to Charnwit Polcheewin the only coach who managed a club from Thailand to lead to the final of the AFC Champions League . 2002-03 and 2003-04 he won with the club also two runner-up . In his team , which reached the final of the Champions League , were a number of exceptional players like Therdsak Chaiman , Worrawoot Srimaka , Dusit Chalermsan and Anurak Srikerd .
Geylang United / Krung Thai Bank .
In 2006 , he went to Singapore in the S-League to Geylang United He was released after a few months due to lack of success . In 2008 , he took over as coach at Krung Thai Bank F.C. , where he had almost a similar task , as a few years earlier by BEC-Tero . As vice-champion of the club was also qualified for the AFC Champions League . However , he failed to lead the team through the group stage of the season 2008 and beyond . With the Kashima Antlers of Japan and Beijing Guoan F.C . athletic competition was too great . One of the highlights was put under his leadership , yet the club . In the group match against the Vietnam club Nam Dinh F.C . his team won with 9-1 , but also lost four weeks later with 1-8 against Kashima Antlers . At the end of the National Football League season , he reached the Krung Thai 6th Table space . The Erstligalizenz the club was sold at the end of the season at the Bangkok Glass F.C. . Attaphol finished his coaching career with the club and accepted an offer of TTM Samutsakorn . After only a short time in office
Muangthong United .
In 2009 , he received an offer from Muangthong United F.C. , which he accepted and changed . He can champion Muang Thong United for 2009 Thai Premier League and Attaphol won Coach of The year for Thai Premier League and he was able to lead Muang Thong United to play AFC Champions League qualifying play-off for the first in the clubs history .
Buriram United .
In 2010 Buspakom moved from Muangthong United to Buriram United F.C. . He received Coach of the Month in Thai Premier League 2 time in June and October . In 2011 , he led Buriram United win 2011 Thai Premier League second time for club and set a record with the most points in the Thai League T1 for 85 point and He led Buriram win 2011 Thai FA Cup by beat Muangthong United F.C . 1-0 and he led Buriram win 2011 Thai League Cup by beat Thai Port F.C . 2-0 . In 2012 , he led Buriram United to the 2012 AFC Champions League group stage . Buriram along with Guangzhou Evergrande F.C . from China , Kashiwa Reysol from Japan and Jeonbuk Hyundai Motors which are all champions from their country . In the first match of Buriram they beat Kashiwa 3-2 and Second Match they beat Guangzhou 1-2 at the Tianhe Stadium . Before losing to Jeonbuk 0-2 and 3-2 with lose Kashiwa and Guangzhou 1-0 and 1-2 respectively and Thai Premier League Attaphol lead Buriram end 4th for table with win 2012 Thai FA Cup and 2012 Thai League Cup .
Bangkok Glass .
In 2013 , he moved from Buriram United to Bangkok Glass F.C. .
Individual
- Thai Premier League Coach of the Year ( 3 ) : 2001-02 , 2009 , 2013

View file

@ -0,0 +1,27 @@
Arnulf Øverland Ole Peter Arnulf Øverland ( 27 April 1889 25 March 1968 ) was a Norwegian poet and artist . He is principally known for his poetry which served to inspire the Norwegian resistance movement during the German occupation of Norway during World War II .
Biography .
Øverland was born in Kristiansund and raised in Bergen . His parents were Peter Anton Øverland ( 18521906 ) and Hanna Hage ( 18541939 ) . The early death of his father , left the family economically stressed . He was able to attend Bergen Cathedral School and in 1904 Kristiania Cathedral School . He graduated in 1907 and for a time studied philology at University of Kristiania . Øverland published his first collection of poems ( 1911 ) .
Øverland became a communist sympathizer from the early 1920s and became a member of Mot Dag . He also served as chairman of the Norwegian Students Society 192328 . He changed his stand in 1937 , partly as an expression of dissent against the ongoing Moscow Trials . He was an avid opponent of Nazism and in 1936 he wrote the poem Du må ikke sove which was printed in the journal Samtiden . It ends with . ( I thought: : Something is imminent . Our era is over Europes on fire! ) . Probably the most famous line of the poem is ( You mustnt endure so well the injustice that doesnt affect you yourself! )
During the German occupation of Norway from 1940 in World War II , he wrote to inspire the Norwegian resistance movement . He wrote a series of poems which were clandestinely distributed , leading to the arrest of both him and his future wife Margrete Aamot Øverland in 1941 . Arnulf Øverland was held first in the prison camp of Grini before being transferred to Sachsenhausen concentration camp in Germany . He spent a four-year imprisonment until the liberation of Norway in 1945 . His poems were later collected in Vi overlever alt and published in 1945 .
Øverland played an important role in the Norwegian language struggle in the post-war era . He became a noted supporter for the conservative written form of Norwegian called Riksmål , he was president of Riksmålsforbundet ( an organization in support of Riksmål ) from 1947 to 1956 . In addition , Øverland adhered to the traditionalist style of writing , criticising modernist poetry on several occasions . His speech Tungetale fra parnasset , published in Arbeiderbladet in 1954 , initiated the so-called Glossolalia debate .
Personal life .
In 1918 he had married the singer Hildur Arntzen ( 18881957 ) . Their marriage was dissolved in 1939 . In 1940 , he married Bartholine Eufemia Leganger ( 19031995 ) . They separated shortly after , and were officially divorced in 1945 . Øverland was married to journalist Margrete Aamot Øverland ( 19131978 ) during June 1945 . In 1946 , the Norwegian Parliament arranged for Arnulf and Margrete Aamot Øverland to reside at the Grotten . He lived there until his death in 1968 and she lived there for another ten years until her death in 1978 . Arnulf Øverland was buried at Vår Frelsers Gravlund in Oslo . Joseph Grimeland designed the bust of Arnulf Øverland ( bronze , 1970 ) at his grave site .
Selected Works .
- Den ensomme fest ( 1911 )
- Berget det blå ( 1927 )
- En Hustavle ( 1929 )
- Den røde front ( 1937 )
- Vi overlever alt ( 1945 )
- Sverdet bak døren ( 1956 )
- Livets minutter ( 1965 )
Awards .
- Gyldendals Endowment ( 1935 )
- Dobloug Prize ( 1951 )
- Mads Wiel Nygaards legat ( 1961 )

View file

@ -0,0 +1,47 @@
import asyncio
import cognee
from cognee.shared.logging_utils import setup_logging, INFO
from cognee.api.v1.search import SearchType
with open("data/biography_1.txt", "r", encoding="utf-8") as f:
biography_1 = f.read()
with open("data/biography_2.txt", "r", encoding="utf-8") as f:
biography_2 = f.read()
async def main():
await cognee.prune.prune_data()
await cognee.prune.prune_system(metadata=True)
await cognee.add([biography_1, biography_2])
await cognee.cognify(temporal_cognify=True)
queries = [
"What happened before 1980?",
"What happened after 2010?",
"What happened between 2000 and 2006?",
"What happened between 1903 and 1995, I am interested in the Selected Works of Arnulf Øverland Ole Peter Arnulf Øverland?",
"Who is Attaphol Buspakom Attaphol Buspakom?",
"Who was Arnulf Øverland?",
]
for query_text in queries:
search_results = await cognee.search(
query_type=SearchType.TEMPORAL,
query_text=query_text,
top_k=15,
)
print(f"Query: {query_text}")
print(f"Results: {search_results}\n")
if __name__ == "__main__":
logger = setup_logging(log_level=INFO)
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
loop.run_until_complete(main())
finally:
loop.run_until_complete(loop.shutdown_asyncgens())

View file

@ -1,137 +0,0 @@
import asyncio
from os import path
from typing import Any
from pydantic import SkipValidation
from cognee.api.v1.visualize.visualize import visualize_graph
from cognee.infrastructure.engine import DataPoint
from cognee.infrastructure.engine.models.Edge import Edge
from cognee.tasks.storage import add_data_points
import cognee
class Clothes(DataPoint):
name: str
description: str
class Object(DataPoint):
name: str
description: str
has_clothes: list[Clothes]
class Person(DataPoint):
name: str
description: str
has_items: SkipValidation[Any] # (Edge, list[Clothes])
has_objects: SkipValidation[Any] # (Edge, list[Object])
knows: SkipValidation[Any] # (Edge, list["Person"])
async def main():
# Clear the database for a clean state
await cognee.prune.prune_data()
await cognee.prune.prune_system(metadata=True)
# Create clothes items
item1 = Clothes(name="Shirt", description="A blue shirt")
item2 = Clothes(name="Pants", description="Black pants")
item3 = Clothes(name="Jacket", description="Leather jacket")
# Create object with simple relationship to clothes
object1 = Object(
name="Closet", description="A wooden closet", has_clothes=[item1, item2, item3]
)
# Create people with various weighted relationships
person1 = Person(
name="John",
description="A software engineer",
# Single weight (backward compatible)
has_items=(Edge(weight=0.8, relationship_type="owns"), [item1, item2]),
# Simple relationship without weights
has_objects=(Edge(relationship_type="stores_in"), [object1]),
knows=[],
)
person2 = Person(
name="Alice",
description="A designer",
# Multiple weights on edge
has_items=(
Edge(
weights={
"ownership": 0.9,
"frequency_of_use": 0.7,
"emotional_attachment": 0.8,
"monetary_value": 0.6,
},
relationship_type="owns",
),
[item3],
),
has_objects=(Edge(relationship_type="uses"), [object1]),
knows=[],
)
person3 = Person(
name="Bob",
description="A friend",
# Mixed: single weight + multiple weights
has_items=(
Edge(
weight=0.5, # Default weight
weights={"trust_level": 0.9, "communication_frequency": 0.6},
relationship_type="borrows",
),
[item1],
),
has_objects=[],
knows=[],
)
# Create relationships between people with multiple weights
person1.knows = (
Edge(
weights={
"friendship_strength": 0.9,
"trust_level": 0.8,
"years_known": 0.7,
"shared_interests": 0.6,
},
relationship_type="friend",
),
[person2, person3],
)
person2.knows = (
Edge(
weights={"professional_collaboration": 0.8, "personal_friendship": 0.6},
relationship_type="colleague",
),
[person1],
)
all_data_points = [item1, item2, item3, object1, person1, person2, person3]
# Add data points to the graph
await add_data_points(all_data_points)
# Visualize the graph
graph_visualization_path = path.join(
path.dirname(__file__), "weighted_graph_visualization.html"
)
await visualize_graph(graph_visualization_path)
print("Graph with multiple weighted edges has been created and visualized!")
print(f"Visualization saved to: {graph_visualization_path}")
print("\nFeatures demonstrated:")
print("- Single weight edges (backward compatible)")
print("- Multiple weights on single edges")
print("- Mixed single + multiple weights")
print("- Hover over edges to see all weight information")
print("- Different visual styling for single vs. multiple weighted edges")
if __name__ == "__main__":
asyncio.run(main())