repo_code_snippets / source_snippets /agent-knowledge-generator.jsonl
PeytonT's picture
Upload folder using huggingface_hub
d67f29d verified
{"repo_id":"agent-knowledge-generator","entity_id":"py:tests.conftest","uri":"program://agent-knowledge-generator/module/tests.conftest#L1-L54","kind":"module","name":"tests.conftest","path":"tests/conftest.py","language":"python","start_line":1,"end_line":54,"context_start_line":1,"context_end_line":54,"code":"import pytest\nimport os\nimport sys\nfrom unittest.mock import Mock, patch\nimport numpy as np\n\n# Add the src directory to the Python path\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n\n# Create mock for sentence transformers before any tests run\n@pytest.fixture(autouse=True)\ndef mock_dependencies():\n \"\"\"Mock external dependencies for all tests.\"\"\"\n mock_sentence_transformer = Mock()\n mock_sentence_transformer.encode.return_value = np.random.rand(1, 384).astype('float32')\n \n with patch.dict('sys.modules', {\n 'sentence_transformers': Mock(),\n 'sentence_transformers.SentenceTransformer': Mock(return_value=mock_sentence_transformer),\n 'tensorflow': Mock(),\n 'torch': Mock()\n }):\n yield\n\n@pytest.fixture\ndef test_data_dir(tmp_path):\n \"\"\"Create a temporary directory for test data.\"\"\"\n data_dir = tmp_path / \"test_data\"\n data_dir.mkdir()\n return data_dir\n\n@pytest.fixture\ndef test_config():\n \"\"\"Return a test configuration dictionary.\"\"\"\n return {\n 'api': {\n 'host': 'localhost',\n 'port': 8000\n },\n 'embedding': {\n 'default_model': 'sentence-transformers/all-MiniLM-L6-v2',\n 'fallback_model': 'sentence-transformers/paraphrase-MiniLM-L3-v2',\n 'dimension': 384\n },\n 'vector_store': {\n 'index_type': 'flat',\n 'max_batch_size': 100\n },\n 'openai': {\n 'model': 'gpt-4',\n 'temperature': 0.7,\n 'max_tokens': 2000\n }\n } ","source_hash":"6e8fd33cb63298d33534420107fd18ed9a530fa4a53a2c24ad4eee7aec0e8b85","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:tests.conftest.mock_dependencies","uri":"program://agent-knowledge-generator/function/tests.conftest.mock_dependencies#L12-L23","kind":"function","name":"mock_dependencies","path":"tests/conftest.py","language":"python","start_line":12,"end_line":23,"context_start_line":1,"context_end_line":43,"code":"import pytest\nimport os\nimport sys\nfrom unittest.mock import Mock, patch\nimport numpy as np\n\n# Add the src directory to the Python path\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n\n# Create mock for sentence transformers before any tests run\n@pytest.fixture(autouse=True)\ndef mock_dependencies():\n \"\"\"Mock external dependencies for all tests.\"\"\"\n mock_sentence_transformer = Mock()\n mock_sentence_transformer.encode.return_value = np.random.rand(1, 384).astype('float32')\n \n with patch.dict('sys.modules', {\n 'sentence_transformers': Mock(),\n 'sentence_transformers.SentenceTransformer': Mock(return_value=mock_sentence_transformer),\n 'tensorflow': Mock(),\n 'torch': Mock()\n }):\n yield\n\n@pytest.fixture\ndef test_data_dir(tmp_path):\n \"\"\"Create a temporary directory for test data.\"\"\"\n data_dir = tmp_path / \"test_data\"\n data_dir.mkdir()\n return data_dir\n\n@pytest.fixture\ndef test_config():\n \"\"\"Return a test configuration dictionary.\"\"\"\n return {\n 'api': {\n 'host': 'localhost',\n 'port': 8000\n },\n 'embedding': {\n 'default_model': 'sentence-transformers/all-MiniLM-L6-v2',\n 'fallback_model': 'sentence-transformers/paraphrase-MiniLM-L3-v2',\n 'dimension': 384","source_hash":"6e8fd33cb63298d33534420107fd18ed9a530fa4a53a2c24ad4eee7aec0e8b85","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:tests.conftest.test_data_dir","uri":"program://agent-knowledge-generator/function/tests.conftest.test_data_dir#L26-L30","kind":"function","name":"test_data_dir","path":"tests/conftest.py","language":"python","start_line":26,"end_line":30,"context_start_line":6,"context_end_line":50,"code":"\n# Add the src directory to the Python path\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n\n# Create mock for sentence transformers before any tests run\n@pytest.fixture(autouse=True)\ndef mock_dependencies():\n \"\"\"Mock external dependencies for all tests.\"\"\"\n mock_sentence_transformer = Mock()\n mock_sentence_transformer.encode.return_value = np.random.rand(1, 384).astype('float32')\n \n with patch.dict('sys.modules', {\n 'sentence_transformers': Mock(),\n 'sentence_transformers.SentenceTransformer': Mock(return_value=mock_sentence_transformer),\n 'tensorflow': Mock(),\n 'torch': Mock()\n }):\n yield\n\n@pytest.fixture\ndef test_data_dir(tmp_path):\n \"\"\"Create a temporary directory for test data.\"\"\"\n data_dir = tmp_path / \"test_data\"\n data_dir.mkdir()\n return data_dir\n\n@pytest.fixture\ndef test_config():\n \"\"\"Return a test configuration dictionary.\"\"\"\n return {\n 'api': {\n 'host': 'localhost',\n 'port': 8000\n },\n 'embedding': {\n 'default_model': 'sentence-transformers/all-MiniLM-L6-v2',\n 'fallback_model': 'sentence-transformers/paraphrase-MiniLM-L3-v2',\n 'dimension': 384\n },\n 'vector_store': {\n 'index_type': 'flat',\n 'max_batch_size': 100\n },\n 'openai': {\n 'model': 'gpt-4',","source_hash":"6e8fd33cb63298d33534420107fd18ed9a530fa4a53a2c24ad4eee7aec0e8b85","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:tests.conftest.test_config","uri":"program://agent-knowledge-generator/function/tests.conftest.test_config#L33-L54","kind":"function","name":"test_config","path":"tests/conftest.py","language":"python","start_line":33,"end_line":54,"context_start_line":13,"context_end_line":54,"code":" \"\"\"Mock external dependencies for all tests.\"\"\"\n mock_sentence_transformer = Mock()\n mock_sentence_transformer.encode.return_value = np.random.rand(1, 384).astype('float32')\n \n with patch.dict('sys.modules', {\n 'sentence_transformers': Mock(),\n 'sentence_transformers.SentenceTransformer': Mock(return_value=mock_sentence_transformer),\n 'tensorflow': Mock(),\n 'torch': Mock()\n }):\n yield\n\n@pytest.fixture\ndef test_data_dir(tmp_path):\n \"\"\"Create a temporary directory for test data.\"\"\"\n data_dir = tmp_path / \"test_data\"\n data_dir.mkdir()\n return data_dir\n\n@pytest.fixture\ndef test_config():\n \"\"\"Return a test configuration dictionary.\"\"\"\n return {\n 'api': {\n 'host': 'localhost',\n 'port': 8000\n },\n 'embedding': {\n 'default_model': 'sentence-transformers/all-MiniLM-L6-v2',\n 'fallback_model': 'sentence-transformers/paraphrase-MiniLM-L3-v2',\n 'dimension': 384\n },\n 'vector_store': {\n 'index_type': 'flat',\n 'max_batch_size': 100\n },\n 'openai': {\n 'model': 'gpt-4',\n 'temperature': 0.7,\n 'max_tokens': 2000\n }\n } ","source_hash":"6e8fd33cb63298d33534420107fd18ed9a530fa4a53a2c24ad4eee7aec0e8b85","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:tests.test_vector_store","uri":"program://agent-knowledge-generator/module/tests.test_vector_store#L1-L62","kind":"module","name":"tests.test_vector_store","path":"tests/test_vector_store.py","language":"python","start_line":1,"end_line":62,"context_start_line":1,"context_end_line":62,"code":"import pytest\nimport numpy as np\nimport os\nimport sys\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nfrom src.database.vector_store import VectorStore\n\n@pytest.fixture\ndef vector_store():\n \"\"\"Create a real VectorStore instance.\"\"\"\n return VectorStore()\n\ndef test_preprocess_text(vector_store):\n \"\"\"Test text preprocessing.\"\"\"\n text = \"Hello, World! This is a TEST.\"\n words = vector_store._preprocess_text(text)\n assert words == ['hello', 'world', 'this', 'is', 'a', 'test']\n\ndef test_basic_embedding_flow(vector_store):\n \"\"\"Test the basic flow of adding and searching texts.\"\"\"\n # Add some texts\n texts = [\"This is a test document\", \"Another test document\"]\n metadata = [{\"type\": \"test1\"}, {\"type\": \"test2\"}]\n \n # Add texts to store\n ids = vector_store.add_texts(texts, metadata)\n assert len(ids) == 2\n \n # Search for similar texts\n results = vector_store.search(\"test document\", k=2)\n assert len(results) == 2\n assert all('score' in r for r in results)\n assert all('metadata' in r for r in results)\n\ndef test_empty_text(vector_store):\n \"\"\"Test handling of empty text.\"\"\"\n embedding = vector_store._get_text_embedding(\"\")\n assert embedding.shape == (vector_store.dimension,)\n assert np.all(embedding == 0)\n\ndef test_metadata_storage(vector_store):\n \"\"\"Test metadata storage and retrieval.\"\"\"\n texts = [\"Test document\"]\n metadata = [{\"key\": \"value\"}]\n \n ids = vector_store.add_texts(texts, metadata)\n assert len(ids) == 1\n assert vector_store.metadata[ids[0]] == metadata[0]\n\ndef test_search_with_k(vector_store):\n \"\"\"Test search with different k values.\"\"\"\n # Add multiple texts\n texts = [\"First document\", \"Second document\", \"Third document\"]\n ids = vector_store.add_texts(texts)\n \n # Search with different k values\n results1 = vector_store.search(\"document\", k=1)\n results2 = vector_store.search(\"document\", k=2)\n \n assert len(results1) == 1\n assert len(results2) == 2 ","source_hash":"7d223ddadf8bceadc5029f525317fba34b4a3854107f1b139df997df1ca08677","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:tests.test_vector_store.vector_store","uri":"program://agent-knowledge-generator/function/tests.test_vector_store.vector_store#L10-L12","kind":"function","name":"vector_store","path":"tests/test_vector_store.py","language":"python","start_line":10,"end_line":12,"context_start_line":1,"context_end_line":32,"code":"import pytest\nimport numpy as np\nimport os\nimport sys\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nfrom src.database.vector_store import VectorStore\n\n@pytest.fixture\ndef vector_store():\n \"\"\"Create a real VectorStore instance.\"\"\"\n return VectorStore()\n\ndef test_preprocess_text(vector_store):\n \"\"\"Test text preprocessing.\"\"\"\n text = \"Hello, World! This is a TEST.\"\n words = vector_store._preprocess_text(text)\n assert words == ['hello', 'world', 'this', 'is', 'a', 'test']\n\ndef test_basic_embedding_flow(vector_store):\n \"\"\"Test the basic flow of adding and searching texts.\"\"\"\n # Add some texts\n texts = [\"This is a test document\", \"Another test document\"]\n metadata = [{\"type\": \"test1\"}, {\"type\": \"test2\"}]\n \n # Add texts to store\n ids = vector_store.add_texts(texts, metadata)\n assert len(ids) == 2\n \n # Search for similar texts\n results = vector_store.search(\"test document\", k=2)\n assert len(results) == 2","source_hash":"7d223ddadf8bceadc5029f525317fba34b4a3854107f1b139df997df1ca08677","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:tests.test_vector_store.test_preprocess_text","uri":"program://agent-knowledge-generator/function/tests.test_vector_store.test_preprocess_text#L14-L18","kind":"function","name":"test_preprocess_text","path":"tests/test_vector_store.py","language":"python","start_line":14,"end_line":18,"context_start_line":1,"context_end_line":38,"code":"import pytest\nimport numpy as np\nimport os\nimport sys\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nfrom src.database.vector_store import VectorStore\n\n@pytest.fixture\ndef vector_store():\n \"\"\"Create a real VectorStore instance.\"\"\"\n return VectorStore()\n\ndef test_preprocess_text(vector_store):\n \"\"\"Test text preprocessing.\"\"\"\n text = \"Hello, World! This is a TEST.\"\n words = vector_store._preprocess_text(text)\n assert words == ['hello', 'world', 'this', 'is', 'a', 'test']\n\ndef test_basic_embedding_flow(vector_store):\n \"\"\"Test the basic flow of adding and searching texts.\"\"\"\n # Add some texts\n texts = [\"This is a test document\", \"Another test document\"]\n metadata = [{\"type\": \"test1\"}, {\"type\": \"test2\"}]\n \n # Add texts to store\n ids = vector_store.add_texts(texts, metadata)\n assert len(ids) == 2\n \n # Search for similar texts\n results = vector_store.search(\"test document\", k=2)\n assert len(results) == 2\n assert all('score' in r for r in results)\n assert all('metadata' in r for r in results)\n\ndef test_empty_text(vector_store):\n \"\"\"Test handling of empty text.\"\"\"\n embedding = vector_store._get_text_embedding(\"\")","source_hash":"7d223ddadf8bceadc5029f525317fba34b4a3854107f1b139df997df1ca08677","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:tests.test_vector_store.test_basic_embedding_flow","uri":"program://agent-knowledge-generator/function/tests.test_vector_store.test_basic_embedding_flow#L20-L34","kind":"function","name":"test_basic_embedding_flow","path":"tests/test_vector_store.py","language":"python","start_line":20,"end_line":34,"context_start_line":1,"context_end_line":54,"code":"import pytest\nimport numpy as np\nimport os\nimport sys\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nfrom src.database.vector_store import VectorStore\n\n@pytest.fixture\ndef vector_store():\n \"\"\"Create a real VectorStore instance.\"\"\"\n return VectorStore()\n\ndef test_preprocess_text(vector_store):\n \"\"\"Test text preprocessing.\"\"\"\n text = \"Hello, World! This is a TEST.\"\n words = vector_store._preprocess_text(text)\n assert words == ['hello', 'world', 'this', 'is', 'a', 'test']\n\ndef test_basic_embedding_flow(vector_store):\n \"\"\"Test the basic flow of adding and searching texts.\"\"\"\n # Add some texts\n texts = [\"This is a test document\", \"Another test document\"]\n metadata = [{\"type\": \"test1\"}, {\"type\": \"test2\"}]\n \n # Add texts to store\n ids = vector_store.add_texts(texts, metadata)\n assert len(ids) == 2\n \n # Search for similar texts\n results = vector_store.search(\"test document\", k=2)\n assert len(results) == 2\n assert all('score' in r for r in results)\n assert all('metadata' in r for r in results)\n\ndef test_empty_text(vector_store):\n \"\"\"Test handling of empty text.\"\"\"\n embedding = vector_store._get_text_embedding(\"\")\n assert embedding.shape == (vector_store.dimension,)\n assert np.all(embedding == 0)\n\ndef test_metadata_storage(vector_store):\n \"\"\"Test metadata storage and retrieval.\"\"\"\n texts = [\"Test document\"]\n metadata = [{\"key\": \"value\"}]\n \n ids = vector_store.add_texts(texts, metadata)\n assert len(ids) == 1\n assert vector_store.metadata[ids[0]] == metadata[0]\n\ndef test_search_with_k(vector_store):\n \"\"\"Test search with different k values.\"\"\"\n # Add multiple texts\n texts = [\"First document\", \"Second document\", \"Third document\"]","source_hash":"7d223ddadf8bceadc5029f525317fba34b4a3854107f1b139df997df1ca08677","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:tests.test_vector_store.test_empty_text","uri":"program://agent-knowledge-generator/function/tests.test_vector_store.test_empty_text#L36-L40","kind":"function","name":"test_empty_text","path":"tests/test_vector_store.py","language":"python","start_line":36,"end_line":40,"context_start_line":16,"context_end_line":60,"code":" text = \"Hello, World! This is a TEST.\"\n words = vector_store._preprocess_text(text)\n assert words == ['hello', 'world', 'this', 'is', 'a', 'test']\n\ndef test_basic_embedding_flow(vector_store):\n \"\"\"Test the basic flow of adding and searching texts.\"\"\"\n # Add some texts\n texts = [\"This is a test document\", \"Another test document\"]\n metadata = [{\"type\": \"test1\"}, {\"type\": \"test2\"}]\n \n # Add texts to store\n ids = vector_store.add_texts(texts, metadata)\n assert len(ids) == 2\n \n # Search for similar texts\n results = vector_store.search(\"test document\", k=2)\n assert len(results) == 2\n assert all('score' in r for r in results)\n assert all('metadata' in r for r in results)\n\ndef test_empty_text(vector_store):\n \"\"\"Test handling of empty text.\"\"\"\n embedding = vector_store._get_text_embedding(\"\")\n assert embedding.shape == (vector_store.dimension,)\n assert np.all(embedding == 0)\n\ndef test_metadata_storage(vector_store):\n \"\"\"Test metadata storage and retrieval.\"\"\"\n texts = [\"Test document\"]\n metadata = [{\"key\": \"value\"}]\n \n ids = vector_store.add_texts(texts, metadata)\n assert len(ids) == 1\n assert vector_store.metadata[ids[0]] == metadata[0]\n\ndef test_search_with_k(vector_store):\n \"\"\"Test search with different k values.\"\"\"\n # Add multiple texts\n texts = [\"First document\", \"Second document\", \"Third document\"]\n ids = vector_store.add_texts(texts)\n \n # Search with different k values\n results1 = vector_store.search(\"document\", k=1)\n results2 = vector_store.search(\"document\", k=2)\n ","source_hash":"7d223ddadf8bceadc5029f525317fba34b4a3854107f1b139df997df1ca08677","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:tests.test_vector_store.test_metadata_storage","uri":"program://agent-knowledge-generator/function/tests.test_vector_store.test_metadata_storage#L42-L49","kind":"function","name":"test_metadata_storage","path":"tests/test_vector_store.py","language":"python","start_line":42,"end_line":49,"context_start_line":22,"context_end_line":62,"code":" # Add some texts\n texts = [\"This is a test document\", \"Another test document\"]\n metadata = [{\"type\": \"test1\"}, {\"type\": \"test2\"}]\n \n # Add texts to store\n ids = vector_store.add_texts(texts, metadata)\n assert len(ids) == 2\n \n # Search for similar texts\n results = vector_store.search(\"test document\", k=2)\n assert len(results) == 2\n assert all('score' in r for r in results)\n assert all('metadata' in r for r in results)\n\ndef test_empty_text(vector_store):\n \"\"\"Test handling of empty text.\"\"\"\n embedding = vector_store._get_text_embedding(\"\")\n assert embedding.shape == (vector_store.dimension,)\n assert np.all(embedding == 0)\n\ndef test_metadata_storage(vector_store):\n \"\"\"Test metadata storage and retrieval.\"\"\"\n texts = [\"Test document\"]\n metadata = [{\"key\": \"value\"}]\n \n ids = vector_store.add_texts(texts, metadata)\n assert len(ids) == 1\n assert vector_store.metadata[ids[0]] == metadata[0]\n\ndef test_search_with_k(vector_store):\n \"\"\"Test search with different k values.\"\"\"\n # Add multiple texts\n texts = [\"First document\", \"Second document\", \"Third document\"]\n ids = vector_store.add_texts(texts)\n \n # Search with different k values\n results1 = vector_store.search(\"document\", k=1)\n results2 = vector_store.search(\"document\", k=2)\n \n assert len(results1) == 1\n assert len(results2) == 2 ","source_hash":"7d223ddadf8bceadc5029f525317fba34b4a3854107f1b139df997df1ca08677","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:tests.test_vector_store.test_search_with_k","uri":"program://agent-knowledge-generator/function/tests.test_vector_store.test_search_with_k#L51-L62","kind":"function","name":"test_search_with_k","path":"tests/test_vector_store.py","language":"python","start_line":51,"end_line":62,"context_start_line":31,"context_end_line":62,"code":" results = vector_store.search(\"test document\", k=2)\n assert len(results) == 2\n assert all('score' in r for r in results)\n assert all('metadata' in r for r in results)\n\ndef test_empty_text(vector_store):\n \"\"\"Test handling of empty text.\"\"\"\n embedding = vector_store._get_text_embedding(\"\")\n assert embedding.shape == (vector_store.dimension,)\n assert np.all(embedding == 0)\n\ndef test_metadata_storage(vector_store):\n \"\"\"Test metadata storage and retrieval.\"\"\"\n texts = [\"Test document\"]\n metadata = [{\"key\": \"value\"}]\n \n ids = vector_store.add_texts(texts, metadata)\n assert len(ids) == 1\n assert vector_store.metadata[ids[0]] == metadata[0]\n\ndef test_search_with_k(vector_store):\n \"\"\"Test search with different k values.\"\"\"\n # Add multiple texts\n texts = [\"First document\", \"Second document\", \"Third document\"]\n ids = vector_store.add_texts(texts)\n \n # Search with different k values\n results1 = vector_store.search(\"document\", k=1)\n results2 = vector_store.search(\"document\", k=2)\n \n assert len(results1) == 1\n assert len(results2) == 2 ","source_hash":"7d223ddadf8bceadc5029f525317fba34b4a3854107f1b139df997df1ca08677","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:tests.test_system_logger","uri":"program://agent-knowledge-generator/module/tests.test_system_logger#L1-L126","kind":"module","name":"tests.test_system_logger","path":"tests/test_system_logger.py","language":"python","start_line":1,"end_line":126,"context_start_line":1,"context_end_line":126,"code":"import pytest\nimport json\nimport os\nfrom datetime import datetime\nimport sys\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nfrom src.utils.logger import SystemLogger\n\n@pytest.fixture\ndef temp_log_files(tmp_path):\n actions_log = tmp_path / \"actions.log\"\n thoughts_log = tmp_path / \"thoughts.log\"\n return str(actions_log), str(thoughts_log)\n\n@pytest.fixture\ndef system_logger(temp_log_files):\n actions_log, thoughts_log = temp_log_files\n return SystemLogger(actions_log_path=actions_log, thoughts_log_path=thoughts_log)\n\ndef test_log_file_creation(temp_log_files):\n actions_log, thoughts_log = temp_log_files\n SystemLogger(actions_log_path=actions_log, thoughts_log_path=thoughts_log)\n \n assert os.path.exists(actions_log)\n assert os.path.exists(thoughts_log)\n\ndef test_log_action(system_logger, temp_log_files):\n actions_log, _ = temp_log_files\n \n test_action = \"Test action\"\n test_metadata = {\"key\": \"value\"}\n \n system_logger.log_action(test_action, test_metadata)\n \n with open(actions_log, 'r') as f:\n log_entry = json.loads(f.read().strip())\n \n assert log_entry[\"type\"] == \"action\"\n assert log_entry[\"message\"] == test_action\n assert log_entry[\"metadata\"] == test_metadata\n assert \"timestamp\" in log_entry\n\ndef test_log_thought(system_logger, temp_log_files):\n _, thoughts_log = temp_log_files\n \n test_thought = \"Test thought\"\n test_metadata = {\"key\": \"value\"}\n \n system_logger.log_thought(test_thought, test_metadata)\n \n with open(thoughts_log, 'r') as f:\n log_entry = json.loads(f.read().strip())\n \n assert log_entry[\"type\"] == \"thought\"\n assert log_entry[\"message\"] == test_thought\n assert log_entry[\"metadata\"] == test_metadata\n assert \"timestamp\" in log_entry\n\ndef test_log_without_metadata(system_logger, temp_log_files):\n actions_log, _ = temp_log_files\n \n test_action = \"Test action without metadata\"\n system_logger.log_action(test_action)\n \n with open(actions_log, 'r') as f:\n log_entry = json.loads(f.read().strip())\n \n assert log_entry[\"type\"] == \"action\"\n assert log_entry[\"message\"] == test_action\n assert \"metadata\" not in log_entry\n\ndef test_get_recent_actions(system_logger, temp_log_files):\n # Log multiple actions\n for i in range(5):\n system_logger.log_action(f\"Action {i}\")\n \n # Get recent actions\n recent_actions = system_logger.get_recent_actions(limit=3)\n \n assert len(recent_actions) == 3\n assert recent_actions[-1][\"message\"] == \"Action 4\"\n assert recent_actions[-2][\"message\"] == \"Action 3\"\n assert recent_actions[-3][\"message\"] == \"Action 2\"\n\ndef test_get_recent_thoughts(system_logger, temp_log_files):\n # Log multiple thoughts\n for i in range(5):\n system_logger.log_thought(f\"Thought {i}\")\n \n # Get recent thoughts\n recent_thoughts = system_logger.get_recent_thoughts(limit=3)\n \n assert len(recent_thoughts) == 3\n assert recent_thoughts[-1][\"message\"] == \"Thought 4\"\n assert recent_thoughts[-2][\"message\"] == \"Thought 3\"\n assert recent_thoughts[-3][\"message\"] == \"Thought 2\"\n\ndef test_timestamp_format(system_logger, temp_log_files):\n actions_log, _ = temp_log_files\n \n system_logger.log_action(\"Test timestamp\")\n \n with open(actions_log, 'r') as f:\n log_entry = json.loads(f.read().strip())\n \n # Verify timestamp is in ISO format\n timestamp = log_entry[\"timestamp\"]\n try:\n datetime.fromisoformat(timestamp)\n except ValueError:\n pytest.fail(\"Timestamp is not in ISO format\")\n\ndef test_handle_invalid_json_in_logs(system_logger, temp_log_files):\n actions_log, _ = temp_log_files\n \n # Write invalid JSON to the log file\n with open(actions_log, 'w') as f:\n f.write(\"Invalid JSON\\n\")\n f.write(json.dumps({\"type\": \"action\", \"message\": \"Valid entry\"}) + \"\\n\")\n \n # Should skip invalid JSON and return valid entries\n recent_actions = system_logger.get_recent_actions()\n \n assert len(recent_actions) == 1\n assert recent_actions[0][\"message\"] == \"Valid entry\" ","source_hash":"b8b96652a6663b42e6a900902fca184c018c37c0404d68087d174c27f755a1c2","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:tests.test_system_logger.temp_log_files","uri":"program://agent-knowledge-generator/function/tests.test_system_logger.temp_log_files#L11-L14","kind":"function","name":"temp_log_files","path":"tests/test_system_logger.py","language":"python","start_line":11,"end_line":14,"context_start_line":1,"context_end_line":34,"code":"import pytest\nimport json\nimport os\nfrom datetime import datetime\nimport sys\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nfrom src.utils.logger import SystemLogger\n\n@pytest.fixture\ndef temp_log_files(tmp_path):\n actions_log = tmp_path / \"actions.log\"\n thoughts_log = tmp_path / \"thoughts.log\"\n return str(actions_log), str(thoughts_log)\n\n@pytest.fixture\ndef system_logger(temp_log_files):\n actions_log, thoughts_log = temp_log_files\n return SystemLogger(actions_log_path=actions_log, thoughts_log_path=thoughts_log)\n\ndef test_log_file_creation(temp_log_files):\n actions_log, thoughts_log = temp_log_files\n SystemLogger(actions_log_path=actions_log, thoughts_log_path=thoughts_log)\n \n assert os.path.exists(actions_log)\n assert os.path.exists(thoughts_log)\n\ndef test_log_action(system_logger, temp_log_files):\n actions_log, _ = temp_log_files\n \n test_action = \"Test action\"\n test_metadata = {\"key\": \"value\"}\n \n system_logger.log_action(test_action, test_metadata)","source_hash":"b8b96652a6663b42e6a900902fca184c018c37c0404d68087d174c27f755a1c2","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:tests.test_system_logger.system_logger","uri":"program://agent-knowledge-generator/function/tests.test_system_logger.system_logger#L17-L19","kind":"function","name":"system_logger","path":"tests/test_system_logger.py","language":"python","start_line":17,"end_line":19,"context_start_line":1,"context_end_line":39,"code":"import pytest\nimport json\nimport os\nfrom datetime import datetime\nimport sys\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nfrom src.utils.logger import SystemLogger\n\n@pytest.fixture\ndef temp_log_files(tmp_path):\n actions_log = tmp_path / \"actions.log\"\n thoughts_log = tmp_path / \"thoughts.log\"\n return str(actions_log), str(thoughts_log)\n\n@pytest.fixture\ndef system_logger(temp_log_files):\n actions_log, thoughts_log = temp_log_files\n return SystemLogger(actions_log_path=actions_log, thoughts_log_path=thoughts_log)\n\ndef test_log_file_creation(temp_log_files):\n actions_log, thoughts_log = temp_log_files\n SystemLogger(actions_log_path=actions_log, thoughts_log_path=thoughts_log)\n \n assert os.path.exists(actions_log)\n assert os.path.exists(thoughts_log)\n\ndef test_log_action(system_logger, temp_log_files):\n actions_log, _ = temp_log_files\n \n test_action = \"Test action\"\n test_metadata = {\"key\": \"value\"}\n \n system_logger.log_action(test_action, test_metadata)\n \n with open(actions_log, 'r') as f:\n log_entry = json.loads(f.read().strip())\n \n assert log_entry[\"type\"] == \"action\"","source_hash":"b8b96652a6663b42e6a900902fca184c018c37c0404d68087d174c27f755a1c2","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:tests.test_system_logger.test_log_file_creation","uri":"program://agent-knowledge-generator/function/tests.test_system_logger.test_log_file_creation#L21-L26","kind":"function","name":"test_log_file_creation","path":"tests/test_system_logger.py","language":"python","start_line":21,"end_line":26,"context_start_line":1,"context_end_line":46,"code":"import pytest\nimport json\nimport os\nfrom datetime import datetime\nimport sys\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nfrom src.utils.logger import SystemLogger\n\n@pytest.fixture\ndef temp_log_files(tmp_path):\n actions_log = tmp_path / \"actions.log\"\n thoughts_log = tmp_path / \"thoughts.log\"\n return str(actions_log), str(thoughts_log)\n\n@pytest.fixture\ndef system_logger(temp_log_files):\n actions_log, thoughts_log = temp_log_files\n return SystemLogger(actions_log_path=actions_log, thoughts_log_path=thoughts_log)\n\ndef test_log_file_creation(temp_log_files):\n actions_log, thoughts_log = temp_log_files\n SystemLogger(actions_log_path=actions_log, thoughts_log_path=thoughts_log)\n \n assert os.path.exists(actions_log)\n assert os.path.exists(thoughts_log)\n\ndef test_log_action(system_logger, temp_log_files):\n actions_log, _ = temp_log_files\n \n test_action = \"Test action\"\n test_metadata = {\"key\": \"value\"}\n \n system_logger.log_action(test_action, test_metadata)\n \n with open(actions_log, 'r') as f:\n log_entry = json.loads(f.read().strip())\n \n assert log_entry[\"type\"] == \"action\"\n assert log_entry[\"message\"] == test_action\n assert log_entry[\"metadata\"] == test_metadata\n assert \"timestamp\" in log_entry\n\ndef test_log_thought(system_logger, temp_log_files):\n _, thoughts_log = temp_log_files\n ","source_hash":"b8b96652a6663b42e6a900902fca184c018c37c0404d68087d174c27f755a1c2","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:tests.test_system_logger.test_log_action","uri":"program://agent-knowledge-generator/function/tests.test_system_logger.test_log_action#L28-L42","kind":"function","name":"test_log_action","path":"tests/test_system_logger.py","language":"python","start_line":28,"end_line":42,"context_start_line":8,"context_end_line":62,"code":"from src.utils.logger import SystemLogger\n\n@pytest.fixture\ndef temp_log_files(tmp_path):\n actions_log = tmp_path / \"actions.log\"\n thoughts_log = tmp_path / \"thoughts.log\"\n return str(actions_log), str(thoughts_log)\n\n@pytest.fixture\ndef system_logger(temp_log_files):\n actions_log, thoughts_log = temp_log_files\n return SystemLogger(actions_log_path=actions_log, thoughts_log_path=thoughts_log)\n\ndef test_log_file_creation(temp_log_files):\n actions_log, thoughts_log = temp_log_files\n SystemLogger(actions_log_path=actions_log, thoughts_log_path=thoughts_log)\n \n assert os.path.exists(actions_log)\n assert os.path.exists(thoughts_log)\n\ndef test_log_action(system_logger, temp_log_files):\n actions_log, _ = temp_log_files\n \n test_action = \"Test action\"\n test_metadata = {\"key\": \"value\"}\n \n system_logger.log_action(test_action, test_metadata)\n \n with open(actions_log, 'r') as f:\n log_entry = json.loads(f.read().strip())\n \n assert log_entry[\"type\"] == \"action\"\n assert log_entry[\"message\"] == test_action\n assert log_entry[\"metadata\"] == test_metadata\n assert \"timestamp\" in log_entry\n\ndef test_log_thought(system_logger, temp_log_files):\n _, thoughts_log = temp_log_files\n \n test_thought = \"Test thought\"\n test_metadata = {\"key\": \"value\"}\n \n system_logger.log_thought(test_thought, test_metadata)\n \n with open(thoughts_log, 'r') as f:\n log_entry = json.loads(f.read().strip())\n \n assert log_entry[\"type\"] == \"thought\"\n assert log_entry[\"message\"] == test_thought\n assert log_entry[\"metadata\"] == test_metadata\n assert \"timestamp\" in log_entry\n\ndef test_log_without_metadata(system_logger, temp_log_files):\n actions_log, _ = temp_log_files\n ","source_hash":"b8b96652a6663b42e6a900902fca184c018c37c0404d68087d174c27f755a1c2","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:tests.test_system_logger.test_log_thought","uri":"program://agent-knowledge-generator/function/tests.test_system_logger.test_log_thought#L44-L58","kind":"function","name":"test_log_thought","path":"tests/test_system_logger.py","language":"python","start_line":44,"end_line":58,"context_start_line":24,"context_end_line":78,"code":" \n assert os.path.exists(actions_log)\n assert os.path.exists(thoughts_log)\n\ndef test_log_action(system_logger, temp_log_files):\n actions_log, _ = temp_log_files\n \n test_action = \"Test action\"\n test_metadata = {\"key\": \"value\"}\n \n system_logger.log_action(test_action, test_metadata)\n \n with open(actions_log, 'r') as f:\n log_entry = json.loads(f.read().strip())\n \n assert log_entry[\"type\"] == \"action\"\n assert log_entry[\"message\"] == test_action\n assert log_entry[\"metadata\"] == test_metadata\n assert \"timestamp\" in log_entry\n\ndef test_log_thought(system_logger, temp_log_files):\n _, thoughts_log = temp_log_files\n \n test_thought = \"Test thought\"\n test_metadata = {\"key\": \"value\"}\n \n system_logger.log_thought(test_thought, test_metadata)\n \n with open(thoughts_log, 'r') as f:\n log_entry = json.loads(f.read().strip())\n \n assert log_entry[\"type\"] == \"thought\"\n assert log_entry[\"message\"] == test_thought\n assert log_entry[\"metadata\"] == test_metadata\n assert \"timestamp\" in log_entry\n\ndef test_log_without_metadata(system_logger, temp_log_files):\n actions_log, _ = temp_log_files\n \n test_action = \"Test action without metadata\"\n system_logger.log_action(test_action)\n \n with open(actions_log, 'r') as f:\n log_entry = json.loads(f.read().strip())\n \n assert log_entry[\"type\"] == \"action\"\n assert log_entry[\"message\"] == test_action\n assert \"metadata\" not in log_entry\n\ndef test_get_recent_actions(system_logger, temp_log_files):\n # Log multiple actions\n for i in range(5):\n system_logger.log_action(f\"Action {i}\")\n \n # Get recent actions","source_hash":"b8b96652a6663b42e6a900902fca184c018c37c0404d68087d174c27f755a1c2","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:tests.test_system_logger.test_log_without_metadata","uri":"program://agent-knowledge-generator/function/tests.test_system_logger.test_log_without_metadata#L60-L71","kind":"function","name":"test_log_without_metadata","path":"tests/test_system_logger.py","language":"python","start_line":60,"end_line":71,"context_start_line":40,"context_end_line":91,"code":" assert log_entry[\"message\"] == test_action\n assert log_entry[\"metadata\"] == test_metadata\n assert \"timestamp\" in log_entry\n\ndef test_log_thought(system_logger, temp_log_files):\n _, thoughts_log = temp_log_files\n \n test_thought = \"Test thought\"\n test_metadata = {\"key\": \"value\"}\n \n system_logger.log_thought(test_thought, test_metadata)\n \n with open(thoughts_log, 'r') as f:\n log_entry = json.loads(f.read().strip())\n \n assert log_entry[\"type\"] == \"thought\"\n assert log_entry[\"message\"] == test_thought\n assert log_entry[\"metadata\"] == test_metadata\n assert \"timestamp\" in log_entry\n\ndef test_log_without_metadata(system_logger, temp_log_files):\n actions_log, _ = temp_log_files\n \n test_action = \"Test action without metadata\"\n system_logger.log_action(test_action)\n \n with open(actions_log, 'r') as f:\n log_entry = json.loads(f.read().strip())\n \n assert log_entry[\"type\"] == \"action\"\n assert log_entry[\"message\"] == test_action\n assert \"metadata\" not in log_entry\n\ndef test_get_recent_actions(system_logger, temp_log_files):\n # Log multiple actions\n for i in range(5):\n system_logger.log_action(f\"Action {i}\")\n \n # Get recent actions\n recent_actions = system_logger.get_recent_actions(limit=3)\n \n assert len(recent_actions) == 3\n assert recent_actions[-1][\"message\"] == \"Action 4\"\n assert recent_actions[-2][\"message\"] == \"Action 3\"\n assert recent_actions[-3][\"message\"] == \"Action 2\"\n\ndef test_get_recent_thoughts(system_logger, temp_log_files):\n # Log multiple thoughts\n for i in range(5):\n system_logger.log_thought(f\"Thought {i}\")\n \n # Get recent thoughts","source_hash":"b8b96652a6663b42e6a900902fca184c018c37c0404d68087d174c27f755a1c2","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:tests.test_system_logger.test_get_recent_actions","uri":"program://agent-knowledge-generator/function/tests.test_system_logger.test_get_recent_actions#L73-L84","kind":"function","name":"test_get_recent_actions","path":"tests/test_system_logger.py","language":"python","start_line":73,"end_line":84,"context_start_line":53,"context_end_line":104,"code":" log_entry = json.loads(f.read().strip())\n \n assert log_entry[\"type\"] == \"thought\"\n assert log_entry[\"message\"] == test_thought\n assert log_entry[\"metadata\"] == test_metadata\n assert \"timestamp\" in log_entry\n\ndef test_log_without_metadata(system_logger, temp_log_files):\n actions_log, _ = temp_log_files\n \n test_action = \"Test action without metadata\"\n system_logger.log_action(test_action)\n \n with open(actions_log, 'r') as f:\n log_entry = json.loads(f.read().strip())\n \n assert log_entry[\"type\"] == \"action\"\n assert log_entry[\"message\"] == test_action\n assert \"metadata\" not in log_entry\n\ndef test_get_recent_actions(system_logger, temp_log_files):\n # Log multiple actions\n for i in range(5):\n system_logger.log_action(f\"Action {i}\")\n \n # Get recent actions\n recent_actions = system_logger.get_recent_actions(limit=3)\n \n assert len(recent_actions) == 3\n assert recent_actions[-1][\"message\"] == \"Action 4\"\n assert recent_actions[-2][\"message\"] == \"Action 3\"\n assert recent_actions[-3][\"message\"] == \"Action 2\"\n\ndef test_get_recent_thoughts(system_logger, temp_log_files):\n # Log multiple thoughts\n for i in range(5):\n system_logger.log_thought(f\"Thought {i}\")\n \n # Get recent thoughts\n recent_thoughts = system_logger.get_recent_thoughts(limit=3)\n \n assert len(recent_thoughts) == 3\n assert recent_thoughts[-1][\"message\"] == \"Thought 4\"\n assert recent_thoughts[-2][\"message\"] == \"Thought 3\"\n assert recent_thoughts[-3][\"message\"] == \"Thought 2\"\n\ndef test_timestamp_format(system_logger, temp_log_files):\n actions_log, _ = temp_log_files\n \n system_logger.log_action(\"Test timestamp\")\n \n with open(actions_log, 'r') as f:","source_hash":"b8b96652a6663b42e6a900902fca184c018c37c0404d68087d174c27f755a1c2","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:tests.test_system_logger.test_get_recent_thoughts","uri":"program://agent-knowledge-generator/function/tests.test_system_logger.test_get_recent_thoughts#L86-L97","kind":"function","name":"test_get_recent_thoughts","path":"tests/test_system_logger.py","language":"python","start_line":86,"end_line":97,"context_start_line":66,"context_end_line":117,"code":" with open(actions_log, 'r') as f:\n log_entry = json.loads(f.read().strip())\n \n assert log_entry[\"type\"] == \"action\"\n assert log_entry[\"message\"] == test_action\n assert \"metadata\" not in log_entry\n\ndef test_get_recent_actions(system_logger, temp_log_files):\n # Log multiple actions\n for i in range(5):\n system_logger.log_action(f\"Action {i}\")\n \n # Get recent actions\n recent_actions = system_logger.get_recent_actions(limit=3)\n \n assert len(recent_actions) == 3\n assert recent_actions[-1][\"message\"] == \"Action 4\"\n assert recent_actions[-2][\"message\"] == \"Action 3\"\n assert recent_actions[-3][\"message\"] == \"Action 2\"\n\ndef test_get_recent_thoughts(system_logger, temp_log_files):\n # Log multiple thoughts\n for i in range(5):\n system_logger.log_thought(f\"Thought {i}\")\n \n # Get recent thoughts\n recent_thoughts = system_logger.get_recent_thoughts(limit=3)\n \n assert len(recent_thoughts) == 3\n assert recent_thoughts[-1][\"message\"] == \"Thought 4\"\n assert recent_thoughts[-2][\"message\"] == \"Thought 3\"\n assert recent_thoughts[-3][\"message\"] == \"Thought 2\"\n\ndef test_timestamp_format(system_logger, temp_log_files):\n actions_log, _ = temp_log_files\n \n system_logger.log_action(\"Test timestamp\")\n \n with open(actions_log, 'r') as f:\n log_entry = json.loads(f.read().strip())\n \n # Verify timestamp is in ISO format\n timestamp = log_entry[\"timestamp\"]\n try:\n datetime.fromisoformat(timestamp)\n except ValueError:\n pytest.fail(\"Timestamp is not in ISO format\")\n\ndef test_handle_invalid_json_in_logs(system_logger, temp_log_files):\n actions_log, _ = temp_log_files\n \n # Write invalid JSON to the log file","source_hash":"b8b96652a6663b42e6a900902fca184c018c37c0404d68087d174c27f755a1c2","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:tests.test_system_logger.test_timestamp_format","uri":"program://agent-knowledge-generator/function/tests.test_system_logger.test_timestamp_format#L99-L112","kind":"function","name":"test_timestamp_format","path":"tests/test_system_logger.py","language":"python","start_line":99,"end_line":112,"context_start_line":79,"context_end_line":126,"code":" recent_actions = system_logger.get_recent_actions(limit=3)\n \n assert len(recent_actions) == 3\n assert recent_actions[-1][\"message\"] == \"Action 4\"\n assert recent_actions[-2][\"message\"] == \"Action 3\"\n assert recent_actions[-3][\"message\"] == \"Action 2\"\n\ndef test_get_recent_thoughts(system_logger, temp_log_files):\n # Log multiple thoughts\n for i in range(5):\n system_logger.log_thought(f\"Thought {i}\")\n \n # Get recent thoughts\n recent_thoughts = system_logger.get_recent_thoughts(limit=3)\n \n assert len(recent_thoughts) == 3\n assert recent_thoughts[-1][\"message\"] == \"Thought 4\"\n assert recent_thoughts[-2][\"message\"] == \"Thought 3\"\n assert recent_thoughts[-3][\"message\"] == \"Thought 2\"\n\ndef test_timestamp_format(system_logger, temp_log_files):\n actions_log, _ = temp_log_files\n \n system_logger.log_action(\"Test timestamp\")\n \n with open(actions_log, 'r') as f:\n log_entry = json.loads(f.read().strip())\n \n # Verify timestamp is in ISO format\n timestamp = log_entry[\"timestamp\"]\n try:\n datetime.fromisoformat(timestamp)\n except ValueError:\n pytest.fail(\"Timestamp is not in ISO format\")\n\ndef test_handle_invalid_json_in_logs(system_logger, temp_log_files):\n actions_log, _ = temp_log_files\n \n # Write invalid JSON to the log file\n with open(actions_log, 'w') as f:\n f.write(\"Invalid JSON\\n\")\n f.write(json.dumps({\"type\": \"action\", \"message\": \"Valid entry\"}) + \"\\n\")\n \n # Should skip invalid JSON and return valid entries\n recent_actions = system_logger.get_recent_actions()\n \n assert len(recent_actions) == 1\n assert recent_actions[0][\"message\"] == \"Valid entry\" ","source_hash":"b8b96652a6663b42e6a900902fca184c018c37c0404d68087d174c27f755a1c2","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:tests.test_system_logger.test_handle_invalid_json_in_logs","uri":"program://agent-knowledge-generator/function/tests.test_system_logger.test_handle_invalid_json_in_logs#L114-L126","kind":"function","name":"test_handle_invalid_json_in_logs","path":"tests/test_system_logger.py","language":"python","start_line":114,"end_line":126,"context_start_line":94,"context_end_line":126,"code":" assert len(recent_thoughts) == 3\n assert recent_thoughts[-1][\"message\"] == \"Thought 4\"\n assert recent_thoughts[-2][\"message\"] == \"Thought 3\"\n assert recent_thoughts[-3][\"message\"] == \"Thought 2\"\n\ndef test_timestamp_format(system_logger, temp_log_files):\n actions_log, _ = temp_log_files\n \n system_logger.log_action(\"Test timestamp\")\n \n with open(actions_log, 'r') as f:\n log_entry = json.loads(f.read().strip())\n \n # Verify timestamp is in ISO format\n timestamp = log_entry[\"timestamp\"]\n try:\n datetime.fromisoformat(timestamp)\n except ValueError:\n pytest.fail(\"Timestamp is not in ISO format\")\n\ndef test_handle_invalid_json_in_logs(system_logger, temp_log_files):\n actions_log, _ = temp_log_files\n \n # Write invalid JSON to the log file\n with open(actions_log, 'w') as f:\n f.write(\"Invalid JSON\\n\")\n f.write(json.dumps({\"type\": \"action\", \"message\": \"Valid entry\"}) + \"\\n\")\n \n # Should skip invalid JSON and return valid entries\n recent_actions = system_logger.get_recent_actions()\n \n assert len(recent_actions) == 1\n assert recent_actions[0][\"message\"] == \"Valid entry\" ","source_hash":"b8b96652a6663b42e6a900902fca184c018c37c0404d68087d174c27f755a1c2","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:tests.test_api","uri":"program://agent-knowledge-generator/module/tests.test_api#L1-L67","kind":"module","name":"tests.test_api","path":"tests/test_api.py","language":"python","start_line":1,"end_line":67,"context_start_line":1,"context_end_line":67,"code":"import pytest\nfrom fastapi.testclient import TestClient\nimport os\nimport sys\nfrom dotenv import load_dotenv\n\n# Load environment variables before importing app\nload_dotenv()\n\n# Ensure we have an API key for tests\nif not os.getenv('OPENAI_API_KEY'):\n pytest.skip(\"Skipping tests that require OpenAI API key\", allow_module_level=True)\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nfrom src.api.main import app\n\n@pytest.fixture\ndef client():\n \"\"\"Create a test client.\"\"\"\n return TestClient(app)\n\ndef test_health_check(client):\n \"\"\"Test the health check endpoint.\"\"\"\n response = client.get(\"/health\")\n assert response.status_code == 200\n assert response.json() == {\"status\": \"healthy\"}\n\ndef test_add_and_search_flow(client):\n \"\"\"Test the basic flow of adding texts and searching.\"\"\"\n # First add some texts\n add_response = client.post(\n \"/add-texts\",\n json={\n \"texts\": [\"This is a test document\", \"Another test document\"],\n \"metadata\": [{\"type\": \"test1\"}, {\"type\": \"test2\"}]\n }\n )\n assert add_response.status_code == 200\n assert \"ids\" in add_response.json()\n \n # Then search\n search_response = client.post(\n \"/search\",\n json={\n \"query\": \"test document\",\n \"k\": 2\n }\n )\n assert search_response.status_code == 200\n results = search_response.json()[\"results\"]\n assert len(results) == 2\n assert all('score' in r for r in results)\n assert all('metadata' in r for r in results)\n\ndef test_invalid_requests(client):\n \"\"\"Test handling of invalid requests.\"\"\"\n # Missing required field\n response1 = client.post(\"/add-texts\", json={})\n assert response1.status_code == 422\n \n # Invalid k value\n response2 = client.post(\"/search\", json={\"query\": \"test\", \"k\": -1})\n assert response2.status_code == 422\n \n # Empty query\n response3 = client.post(\"/search\", json={\"query\": \"\", \"k\": 1})\n assert response3.status_code == 200 # Should handle empty query gracefully ","source_hash":"bb6ddb3e844398070bbdb391e83b33fc18d86b7f1e2cfac09a5457371bef3f36","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:tests.test_api.client","uri":"program://agent-knowledge-generator/function/tests.test_api.client#L18-L20","kind":"function","name":"client","path":"tests/test_api.py","language":"python","start_line":18,"end_line":20,"context_start_line":1,"context_end_line":40,"code":"import pytest\nfrom fastapi.testclient import TestClient\nimport os\nimport sys\nfrom dotenv import load_dotenv\n\n# Load environment variables before importing app\nload_dotenv()\n\n# Ensure we have an API key for tests\nif not os.getenv('OPENAI_API_KEY'):\n pytest.skip(\"Skipping tests that require OpenAI API key\", allow_module_level=True)\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nfrom src.api.main import app\n\n@pytest.fixture\ndef client():\n \"\"\"Create a test client.\"\"\"\n return TestClient(app)\n\ndef test_health_check(client):\n \"\"\"Test the health check endpoint.\"\"\"\n response = client.get(\"/health\")\n assert response.status_code == 200\n assert response.json() == {\"status\": \"healthy\"}\n\ndef test_add_and_search_flow(client):\n \"\"\"Test the basic flow of adding texts and searching.\"\"\"\n # First add some texts\n add_response = client.post(\n \"/add-texts\",\n json={\n \"texts\": [\"This is a test document\", \"Another test document\"],\n \"metadata\": [{\"type\": \"test1\"}, {\"type\": \"test2\"}]\n }\n )\n assert add_response.status_code == 200\n assert \"ids\" in add_response.json()\n ","source_hash":"bb6ddb3e844398070bbdb391e83b33fc18d86b7f1e2cfac09a5457371bef3f36","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:tests.test_api.test_health_check","uri":"program://agent-knowledge-generator/function/tests.test_api.test_health_check#L22-L26","kind":"function","name":"test_health_check","path":"tests/test_api.py","language":"python","start_line":22,"end_line":26,"context_start_line":2,"context_end_line":46,"code":"from fastapi.testclient import TestClient\nimport os\nimport sys\nfrom dotenv import load_dotenv\n\n# Load environment variables before importing app\nload_dotenv()\n\n# Ensure we have an API key for tests\nif not os.getenv('OPENAI_API_KEY'):\n pytest.skip(\"Skipping tests that require OpenAI API key\", allow_module_level=True)\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nfrom src.api.main import app\n\n@pytest.fixture\ndef client():\n \"\"\"Create a test client.\"\"\"\n return TestClient(app)\n\ndef test_health_check(client):\n \"\"\"Test the health check endpoint.\"\"\"\n response = client.get(\"/health\")\n assert response.status_code == 200\n assert response.json() == {\"status\": \"healthy\"}\n\ndef test_add_and_search_flow(client):\n \"\"\"Test the basic flow of adding texts and searching.\"\"\"\n # First add some texts\n add_response = client.post(\n \"/add-texts\",\n json={\n \"texts\": [\"This is a test document\", \"Another test document\"],\n \"metadata\": [{\"type\": \"test1\"}, {\"type\": \"test2\"}]\n }\n )\n assert add_response.status_code == 200\n assert \"ids\" in add_response.json()\n \n # Then search\n search_response = client.post(\n \"/search\",\n json={\n \"query\": \"test document\",\n \"k\": 2","source_hash":"bb6ddb3e844398070bbdb391e83b33fc18d86b7f1e2cfac09a5457371bef3f36","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:tests.test_api.test_add_and_search_flow","uri":"program://agent-knowledge-generator/function/tests.test_api.test_add_and_search_flow#L28-L53","kind":"function","name":"test_add_and_search_flow","path":"tests/test_api.py","language":"python","start_line":28,"end_line":53,"context_start_line":8,"context_end_line":67,"code":"load_dotenv()\n\n# Ensure we have an API key for tests\nif not os.getenv('OPENAI_API_KEY'):\n pytest.skip(\"Skipping tests that require OpenAI API key\", allow_module_level=True)\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nfrom src.api.main import app\n\n@pytest.fixture\ndef client():\n \"\"\"Create a test client.\"\"\"\n return TestClient(app)\n\ndef test_health_check(client):\n \"\"\"Test the health check endpoint.\"\"\"\n response = client.get(\"/health\")\n assert response.status_code == 200\n assert response.json() == {\"status\": \"healthy\"}\n\ndef test_add_and_search_flow(client):\n \"\"\"Test the basic flow of adding texts and searching.\"\"\"\n # First add some texts\n add_response = client.post(\n \"/add-texts\",\n json={\n \"texts\": [\"This is a test document\", \"Another test document\"],\n \"metadata\": [{\"type\": \"test1\"}, {\"type\": \"test2\"}]\n }\n )\n assert add_response.status_code == 200\n assert \"ids\" in add_response.json()\n \n # Then search\n search_response = client.post(\n \"/search\",\n json={\n \"query\": \"test document\",\n \"k\": 2\n }\n )\n assert search_response.status_code == 200\n results = search_response.json()[\"results\"]\n assert len(results) == 2\n assert all('score' in r for r in results)\n assert all('metadata' in r for r in results)\n\ndef test_invalid_requests(client):\n \"\"\"Test handling of invalid requests.\"\"\"\n # Missing required field\n response1 = client.post(\"/add-texts\", json={})\n assert response1.status_code == 422\n \n # Invalid k value\n response2 = client.post(\"/search\", json={\"query\": \"test\", \"k\": -1})\n assert response2.status_code == 422\n \n # Empty query\n response3 = client.post(\"/search\", json={\"query\": \"\", \"k\": 1})\n assert response3.status_code == 200 # Should handle empty query gracefully ","source_hash":"bb6ddb3e844398070bbdb391e83b33fc18d86b7f1e2cfac09a5457371bef3f36","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:tests.test_api.test_invalid_requests","uri":"program://agent-knowledge-generator/function/tests.test_api.test_invalid_requests#L55-L67","kind":"function","name":"test_invalid_requests","path":"tests/test_api.py","language":"python","start_line":55,"end_line":67,"context_start_line":35,"context_end_line":67,"code":" \"metadata\": [{\"type\": \"test1\"}, {\"type\": \"test2\"}]\n }\n )\n assert add_response.status_code == 200\n assert \"ids\" in add_response.json()\n \n # Then search\n search_response = client.post(\n \"/search\",\n json={\n \"query\": \"test document\",\n \"k\": 2\n }\n )\n assert search_response.status_code == 200\n results = search_response.json()[\"results\"]\n assert len(results) == 2\n assert all('score' in r for r in results)\n assert all('metadata' in r for r in results)\n\ndef test_invalid_requests(client):\n \"\"\"Test handling of invalid requests.\"\"\"\n # Missing required field\n response1 = client.post(\"/add-texts\", json={})\n assert response1.status_code == 422\n \n # Invalid k value\n response2 = client.post(\"/search\", json={\"query\": \"test\", \"k\": -1})\n assert response2.status_code == 422\n \n # Empty query\n response3 = client.post(\"/search\", json={\"query\": \"\", \"k\": 1})\n assert response3.status_code == 200 # Should handle empty query gracefully ","source_hash":"bb6ddb3e844398070bbdb391e83b33fc18d86b7f1e2cfac09a5457371bef3f36","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:tests.test_knowledge_processor","uri":"program://agent-knowledge-generator/module/tests.test_knowledge_processor#L1-L104","kind":"module","name":"tests.test_knowledge_processor","path":"tests/test_knowledge_processor.py","language":"python","start_line":1,"end_line":104,"context_start_line":1,"context_end_line":104,"code":"import pytest\nfrom unittest.mock import patch, MagicMock\nimport json\nimport os\nimport sys\nfrom dotenv import load_dotenv\n\n# Load environment variables from .env\nload_dotenv()\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nfrom src.chatgpt.knowledge_processor import KnowledgeProcessor\n\n@pytest.fixture\ndef mock_openai():\n \"\"\"Create a mock OpenAI client.\"\"\"\n mock_response = {\n \"choices\": [{\n \"message\": {\n \"content\": json.dumps({\n \"core_knowledge\": [\n {\n \"title\": \"Test Knowledge\",\n \"description\": \"Test Description\"\n }\n ],\n \"tools\": [\n {\n \"name\": \"test_tool\",\n \"description\": \"Tool Description\"\n }\n ],\n \"examples\": [\n {\n \"query\": \"Test Query\",\n \"expected_response\": \"Test Response\"\n }\n ]\n })\n }\n }]\n }\n\n # Create a proper mock response\n mock_completion = MagicMock()\n mock_completion.choices = [\n MagicMock(\n message=MagicMock(\n content=mock_response[\"choices\"][0][\"message\"][\"content\"]\n )\n )\n ]\n \n # Set up the mock client\n mock_instance = MagicMock()\n mock_instance.chat.completions.create.return_value = mock_completion\n \n with patch('openai.OpenAI', return_value=mock_instance):\n yield mock_instance\n\n@pytest.fixture\ndef knowledge_processor(mock_openai):\n \"\"\"Create a KnowledgeProcessor instance with mocked OpenAI client.\"\"\"\n # Use the API key from environment instead of test-key\n return KnowledgeProcessor(api_key=os.getenv('OPENAI_API_KEY'))\n\ndef test_process_user_input(knowledge_processor):\n \"\"\"Test basic knowledge processing.\"\"\"\n # Process input\n result = knowledge_processor.process_user_input(\"Test input\")\n \n # Verify structure\n assert \"structured_knowledge\" in result\n assert \"text_chunks\" in result\n assert \"metadata\" in result\n \n # Verify content\n knowledge = result[\"structured_knowledge\"]\n assert \"core_knowledge\" in knowledge\n assert \"tools\" in knowledge\n assert \"examples\" in knowledge\n\ndef test_generate_text_chunks(knowledge_processor):\n \"\"\"Test text chunk generation.\"\"\"\n test_knowledge = {\n \"core_knowledge\": [\n {\n \"title\": \"Test\",\n \"description\": \"Description\"\n }\n ],\n \"tools\": [\n {\n \"name\": \"tool\",\n \"description\": \"Tool desc\"\n }\n ],\n \"examples\": []\n }\n \n chunks = knowledge_processor._generate_text_chunks(test_knowledge)\n assert len(chunks) == 2 # One for knowledge, one for tool\n assert any(\"Test\" in chunk for chunk in chunks)\n assert any(\"tool\" in chunk for chunk in chunks) ","source_hash":"2176de273db97e275e071785b7aea5fa72bbc6aac6f3131d3a293422a81f46c0","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:tests.test_knowledge_processor.mock_openai","uri":"program://agent-knowledge-generator/function/tests.test_knowledge_processor.mock_openai#L15-L59","kind":"function","name":"mock_openai","path":"tests/test_knowledge_processor.py","language":"python","start_line":15,"end_line":59,"context_start_line":1,"context_end_line":79,"code":"import pytest\nfrom unittest.mock import patch, MagicMock\nimport json\nimport os\nimport sys\nfrom dotenv import load_dotenv\n\n# Load environment variables from .env\nload_dotenv()\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nfrom src.chatgpt.knowledge_processor import KnowledgeProcessor\n\n@pytest.fixture\ndef mock_openai():\n \"\"\"Create a mock OpenAI client.\"\"\"\n mock_response = {\n \"choices\": [{\n \"message\": {\n \"content\": json.dumps({\n \"core_knowledge\": [\n {\n \"title\": \"Test Knowledge\",\n \"description\": \"Test Description\"\n }\n ],\n \"tools\": [\n {\n \"name\": \"test_tool\",\n \"description\": \"Tool Description\"\n }\n ],\n \"examples\": [\n {\n \"query\": \"Test Query\",\n \"expected_response\": \"Test Response\"\n }\n ]\n })\n }\n }]\n }\n\n # Create a proper mock response\n mock_completion = MagicMock()\n mock_completion.choices = [\n MagicMock(\n message=MagicMock(\n content=mock_response[\"choices\"][0][\"message\"][\"content\"]\n )\n )\n ]\n \n # Set up the mock client\n mock_instance = MagicMock()\n mock_instance.chat.completions.create.return_value = mock_completion\n \n with patch('openai.OpenAI', return_value=mock_instance):\n yield mock_instance\n\n@pytest.fixture\ndef knowledge_processor(mock_openai):\n \"\"\"Create a KnowledgeProcessor instance with mocked OpenAI client.\"\"\"\n # Use the API key from environment instead of test-key\n return KnowledgeProcessor(api_key=os.getenv('OPENAI_API_KEY'))\n\ndef test_process_user_input(knowledge_processor):\n \"\"\"Test basic knowledge processing.\"\"\"\n # Process input\n result = knowledge_processor.process_user_input(\"Test input\")\n \n # Verify structure\n assert \"structured_knowledge\" in result\n assert \"text_chunks\" in result\n assert \"metadata\" in result\n \n # Verify content\n knowledge = result[\"structured_knowledge\"]\n assert \"core_knowledge\" in knowledge","source_hash":"2176de273db97e275e071785b7aea5fa72bbc6aac6f3131d3a293422a81f46c0","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:tests.test_knowledge_processor.knowledge_processor","uri":"program://agent-knowledge-generator/function/tests.test_knowledge_processor.knowledge_processor#L62-L65","kind":"function","name":"knowledge_processor","path":"tests/test_knowledge_processor.py","language":"python","start_line":62,"end_line":65,"context_start_line":42,"context_end_line":85,"code":" }\n\n # Create a proper mock response\n mock_completion = MagicMock()\n mock_completion.choices = [\n MagicMock(\n message=MagicMock(\n content=mock_response[\"choices\"][0][\"message\"][\"content\"]\n )\n )\n ]\n \n # Set up the mock client\n mock_instance = MagicMock()\n mock_instance.chat.completions.create.return_value = mock_completion\n \n with patch('openai.OpenAI', return_value=mock_instance):\n yield mock_instance\n\n@pytest.fixture\ndef knowledge_processor(mock_openai):\n \"\"\"Create a KnowledgeProcessor instance with mocked OpenAI client.\"\"\"\n # Use the API key from environment instead of test-key\n return KnowledgeProcessor(api_key=os.getenv('OPENAI_API_KEY'))\n\ndef test_process_user_input(knowledge_processor):\n \"\"\"Test basic knowledge processing.\"\"\"\n # Process input\n result = knowledge_processor.process_user_input(\"Test input\")\n \n # Verify structure\n assert \"structured_knowledge\" in result\n assert \"text_chunks\" in result\n assert \"metadata\" in result\n \n # Verify content\n knowledge = result[\"structured_knowledge\"]\n assert \"core_knowledge\" in knowledge\n assert \"tools\" in knowledge\n assert \"examples\" in knowledge\n\ndef test_generate_text_chunks(knowledge_processor):\n \"\"\"Test text chunk generation.\"\"\"\n test_knowledge = {","source_hash":"2176de273db97e275e071785b7aea5fa72bbc6aac6f3131d3a293422a81f46c0","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:tests.test_knowledge_processor.test_process_user_input","uri":"program://agent-knowledge-generator/function/tests.test_knowledge_processor.test_process_user_input#L67-L81","kind":"function","name":"test_process_user_input","path":"tests/test_knowledge_processor.py","language":"python","start_line":67,"end_line":81,"context_start_line":47,"context_end_line":101,"code":" MagicMock(\n message=MagicMock(\n content=mock_response[\"choices\"][0][\"message\"][\"content\"]\n )\n )\n ]\n \n # Set up the mock client\n mock_instance = MagicMock()\n mock_instance.chat.completions.create.return_value = mock_completion\n \n with patch('openai.OpenAI', return_value=mock_instance):\n yield mock_instance\n\n@pytest.fixture\ndef knowledge_processor(mock_openai):\n \"\"\"Create a KnowledgeProcessor instance with mocked OpenAI client.\"\"\"\n # Use the API key from environment instead of test-key\n return KnowledgeProcessor(api_key=os.getenv('OPENAI_API_KEY'))\n\ndef test_process_user_input(knowledge_processor):\n \"\"\"Test basic knowledge processing.\"\"\"\n # Process input\n result = knowledge_processor.process_user_input(\"Test input\")\n \n # Verify structure\n assert \"structured_knowledge\" in result\n assert \"text_chunks\" in result\n assert \"metadata\" in result\n \n # Verify content\n knowledge = result[\"structured_knowledge\"]\n assert \"core_knowledge\" in knowledge\n assert \"tools\" in knowledge\n assert \"examples\" in knowledge\n\ndef test_generate_text_chunks(knowledge_processor):\n \"\"\"Test text chunk generation.\"\"\"\n test_knowledge = {\n \"core_knowledge\": [\n {\n \"title\": \"Test\",\n \"description\": \"Description\"\n }\n ],\n \"tools\": [\n {\n \"name\": \"tool\",\n \"description\": \"Tool desc\"\n }\n ],\n \"examples\": []\n }\n \n chunks = knowledge_processor._generate_text_chunks(test_knowledge)","source_hash":"2176de273db97e275e071785b7aea5fa72bbc6aac6f3131d3a293422a81f46c0","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:tests.test_knowledge_processor.test_generate_text_chunks","uri":"program://agent-knowledge-generator/function/tests.test_knowledge_processor.test_generate_text_chunks#L83-L104","kind":"function","name":"test_generate_text_chunks","path":"tests/test_knowledge_processor.py","language":"python","start_line":83,"end_line":104,"context_start_line":63,"context_end_line":104,"code":" \"\"\"Create a KnowledgeProcessor instance with mocked OpenAI client.\"\"\"\n # Use the API key from environment instead of test-key\n return KnowledgeProcessor(api_key=os.getenv('OPENAI_API_KEY'))\n\ndef test_process_user_input(knowledge_processor):\n \"\"\"Test basic knowledge processing.\"\"\"\n # Process input\n result = knowledge_processor.process_user_input(\"Test input\")\n \n # Verify structure\n assert \"structured_knowledge\" in result\n assert \"text_chunks\" in result\n assert \"metadata\" in result\n \n # Verify content\n knowledge = result[\"structured_knowledge\"]\n assert \"core_knowledge\" in knowledge\n assert \"tools\" in knowledge\n assert \"examples\" in knowledge\n\ndef test_generate_text_chunks(knowledge_processor):\n \"\"\"Test text chunk generation.\"\"\"\n test_knowledge = {\n \"core_knowledge\": [\n {\n \"title\": \"Test\",\n \"description\": \"Description\"\n }\n ],\n \"tools\": [\n {\n \"name\": \"tool\",\n \"description\": \"Tool desc\"\n }\n ],\n \"examples\": []\n }\n \n chunks = knowledge_processor._generate_text_chunks(test_knowledge)\n assert len(chunks) == 2 # One for knowledge, one for tool\n assert any(\"Test\" in chunk for chunk in chunks)\n assert any(\"tool\" in chunk for chunk in chunks) ","source_hash":"2176de273db97e275e071785b7aea5fa72bbc6aac6f3131d3a293422a81f46c0","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.database.vector_store","uri":"program://agent-knowledge-generator/module/src.database.vector_store#L1-L108","kind":"module","name":"src.database.vector_store","path":"src/database/vector_store.py","language":"python","start_line":1,"end_line":108,"context_start_line":1,"context_end_line":108,"code":"from typing import List, Dict, Any, Optional\nimport faiss\nimport numpy as np\nfrom loguru import logger\nimport yaml\nimport os\nimport re\nfrom collections import Counter\n\nclass VectorStore:\n def __init__(self, config_path: str = \"config.yaml\"):\n with open(config_path, 'r') as f:\n self.config = yaml.safe_load(f)\n \n self.index = None\n self.metadata = {}\n self.dimension = 100 # Fixed dimension for our simple embeddings\n self.vocabulary = {} # Word to index mapping\n self.next_word_index = 0\n \n def _preprocess_text(self, text: str) -> List[str]:\n \"\"\"Simple text preprocessing.\"\"\"\n # Convert to lowercase and split into words\n words = re.findall(r'\\w+', text.lower())\n return words\n \n def _get_word_index(self, word: str) -> int:\n \"\"\"Get or create index for a word.\"\"\"\n if word not in self.vocabulary:\n self.vocabulary[word] = self.next_word_index\n self.next_word_index += 1\n return self.vocabulary[word]\n \n def _get_text_embedding(self, text: str) -> np.ndarray:\n \"\"\"Create a simple frequency-based embedding for text.\"\"\"\n words = self._preprocess_text(text)\n if not words:\n return np.zeros(self.dimension)\n \n # Count word frequencies\n word_counts = Counter(words)\n \n # Create embedding vector\n embedding = np.zeros(self.dimension)\n for word, count in word_counts.items():\n index = self._get_word_index(word) % self.dimension\n embedding[index] += count\n \n # Normalize the vector\n norm = np.linalg.norm(embedding)\n if norm > 0:\n embedding = embedding / norm\n \n return embedding\n\n def create_index(self, index_type: str = \"flat\") -> None:\n \"\"\"Initialize FAISS index.\"\"\"\n if index_type == \"flat\":\n self.index = faiss.IndexFlatL2(self.dimension)\n elif index_type == \"hnsw\":\n self.index = faiss.IndexHNSWFlat(self.dimension, 32)\n else:\n raise ValueError(f\"Unsupported index type: {index_type}\")\n \n logger.info(f\"Created {index_type} index with dimension {self.dimension}\")\n\n def add_texts(self, texts: List[str], metadata: Optional[List[Dict]] = None) -> List[int]:\n \"\"\"Add texts to the vector store.\"\"\"\n if self.index is None:\n self.create_index()\n \n # Get embeddings for all texts\n embeddings = []\n for text in texts:\n embedding = self._get_text_embedding(text)\n embeddings.append(embedding)\n \n embeddings_array = np.array(embeddings).astype('float32')\n \n if metadata:\n ids = list(range(len(self.metadata), len(self.metadata) + len(texts)))\n for i, meta in zip(ids, metadata):\n self.metadata[i] = meta\n else:\n ids = list(range(len(self.metadata), len(self.metadata) + len(texts)))\n \n self.index.add(embeddings_array)\n return ids\n\n def search(self, query: str, k: int = 5) -> List[Dict[str, Any]]:\n \"\"\"Search the vector store for similar texts.\"\"\"\n query_embedding = self._get_text_embedding(query)\n \n D, I = self.index.search(\n np.array([query_embedding]).astype('float32'), \n k\n )\n \n results = []\n for score, idx in zip(D[0], I[0]):\n result = {\n 'id': int(idx),\n 'score': float(score),\n 'metadata': self.metadata.get(int(idx), {})\n }\n results.append(result)\n \n return results ","source_hash":"dee13db66543a35032a79d476fd2799e5abf482b7e58647269af148f0cf4c264","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.database.vector_store.VectorStore","uri":"program://agent-knowledge-generator/class/src.database.vector_store.VectorStore#L10-L108","kind":"class","name":"VectorStore","path":"src/database/vector_store.py","language":"python","start_line":10,"end_line":108,"context_start_line":1,"context_end_line":108,"code":"from typing import List, Dict, Any, Optional\nimport faiss\nimport numpy as np\nfrom loguru import logger\nimport yaml\nimport os\nimport re\nfrom collections import Counter\n\nclass VectorStore:\n def __init__(self, config_path: str = \"config.yaml\"):\n with open(config_path, 'r') as f:\n self.config = yaml.safe_load(f)\n \n self.index = None\n self.metadata = {}\n self.dimension = 100 # Fixed dimension for our simple embeddings\n self.vocabulary = {} # Word to index mapping\n self.next_word_index = 0\n \n def _preprocess_text(self, text: str) -> List[str]:\n \"\"\"Simple text preprocessing.\"\"\"\n # Convert to lowercase and split into words\n words = re.findall(r'\\w+', text.lower())\n return words\n \n def _get_word_index(self, word: str) -> int:\n \"\"\"Get or create index for a word.\"\"\"\n if word not in self.vocabulary:\n self.vocabulary[word] = self.next_word_index\n self.next_word_index += 1\n return self.vocabulary[word]\n \n def _get_text_embedding(self, text: str) -> np.ndarray:\n \"\"\"Create a simple frequency-based embedding for text.\"\"\"\n words = self._preprocess_text(text)\n if not words:\n return np.zeros(self.dimension)\n \n # Count word frequencies\n word_counts = Counter(words)\n \n # Create embedding vector\n embedding = np.zeros(self.dimension)\n for word, count in word_counts.items():\n index = self._get_word_index(word) % self.dimension\n embedding[index] += count\n \n # Normalize the vector\n norm = np.linalg.norm(embedding)\n if norm > 0:\n embedding = embedding / norm\n \n return embedding\n\n def create_index(self, index_type: str = \"flat\") -> None:\n \"\"\"Initialize FAISS index.\"\"\"\n if index_type == \"flat\":\n self.index = faiss.IndexFlatL2(self.dimension)\n elif index_type == \"hnsw\":\n self.index = faiss.IndexHNSWFlat(self.dimension, 32)\n else:\n raise ValueError(f\"Unsupported index type: {index_type}\")\n \n logger.info(f\"Created {index_type} index with dimension {self.dimension}\")\n\n def add_texts(self, texts: List[str], metadata: Optional[List[Dict]] = None) -> List[int]:\n \"\"\"Add texts to the vector store.\"\"\"\n if self.index is None:\n self.create_index()\n \n # Get embeddings for all texts\n embeddings = []\n for text in texts:\n embedding = self._get_text_embedding(text)\n embeddings.append(embedding)\n \n embeddings_array = np.array(embeddings).astype('float32')\n \n if metadata:\n ids = list(range(len(self.metadata), len(self.metadata) + len(texts)))\n for i, meta in zip(ids, metadata):\n self.metadata[i] = meta\n else:\n ids = list(range(len(self.metadata), len(self.metadata) + len(texts)))\n \n self.index.add(embeddings_array)\n return ids\n\n def search(self, query: str, k: int = 5) -> List[Dict[str, Any]]:\n \"\"\"Search the vector store for similar texts.\"\"\"\n query_embedding = self._get_text_embedding(query)\n \n D, I = self.index.search(\n np.array([query_embedding]).astype('float32'), \n k\n )\n \n results = []\n for score, idx in zip(D[0], I[0]):\n result = {\n 'id': int(idx),\n 'score': float(score),\n 'metadata': self.metadata.get(int(idx), {})\n }\n results.append(result)\n \n return results ","source_hash":"dee13db66543a35032a79d476fd2799e5abf482b7e58647269af148f0cf4c264","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.database.vector_store.__init__","uri":"program://agent-knowledge-generator/function/src.database.vector_store.__init__#L11-L19","kind":"function","name":"__init__","path":"src/database/vector_store.py","language":"python","start_line":11,"end_line":19,"context_start_line":1,"context_end_line":39,"code":"from typing import List, Dict, Any, Optional\nimport faiss\nimport numpy as np\nfrom loguru import logger\nimport yaml\nimport os\nimport re\nfrom collections import Counter\n\nclass VectorStore:\n def __init__(self, config_path: str = \"config.yaml\"):\n with open(config_path, 'r') as f:\n self.config = yaml.safe_load(f)\n \n self.index = None\n self.metadata = {}\n self.dimension = 100 # Fixed dimension for our simple embeddings\n self.vocabulary = {} # Word to index mapping\n self.next_word_index = 0\n \n def _preprocess_text(self, text: str) -> List[str]:\n \"\"\"Simple text preprocessing.\"\"\"\n # Convert to lowercase and split into words\n words = re.findall(r'\\w+', text.lower())\n return words\n \n def _get_word_index(self, word: str) -> int:\n \"\"\"Get or create index for a word.\"\"\"\n if word not in self.vocabulary:\n self.vocabulary[word] = self.next_word_index\n self.next_word_index += 1\n return self.vocabulary[word]\n \n def _get_text_embedding(self, text: str) -> np.ndarray:\n \"\"\"Create a simple frequency-based embedding for text.\"\"\"\n words = self._preprocess_text(text)\n if not words:\n return np.zeros(self.dimension)\n ","source_hash":"dee13db66543a35032a79d476fd2799e5abf482b7e58647269af148f0cf4c264","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.database.vector_store._preprocess_text","uri":"program://agent-knowledge-generator/function/src.database.vector_store._preprocess_text#L21-L25","kind":"function","name":"_preprocess_text","path":"src/database/vector_store.py","language":"python","start_line":21,"end_line":25,"context_start_line":1,"context_end_line":45,"code":"from typing import List, Dict, Any, Optional\nimport faiss\nimport numpy as np\nfrom loguru import logger\nimport yaml\nimport os\nimport re\nfrom collections import Counter\n\nclass VectorStore:\n def __init__(self, config_path: str = \"config.yaml\"):\n with open(config_path, 'r') as f:\n self.config = yaml.safe_load(f)\n \n self.index = None\n self.metadata = {}\n self.dimension = 100 # Fixed dimension for our simple embeddings\n self.vocabulary = {} # Word to index mapping\n self.next_word_index = 0\n \n def _preprocess_text(self, text: str) -> List[str]:\n \"\"\"Simple text preprocessing.\"\"\"\n # Convert to lowercase and split into words\n words = re.findall(r'\\w+', text.lower())\n return words\n \n def _get_word_index(self, word: str) -> int:\n \"\"\"Get or create index for a word.\"\"\"\n if word not in self.vocabulary:\n self.vocabulary[word] = self.next_word_index\n self.next_word_index += 1\n return self.vocabulary[word]\n \n def _get_text_embedding(self, text: str) -> np.ndarray:\n \"\"\"Create a simple frequency-based embedding for text.\"\"\"\n words = self._preprocess_text(text)\n if not words:\n return np.zeros(self.dimension)\n \n # Count word frequencies\n word_counts = Counter(words)\n \n # Create embedding vector\n embedding = np.zeros(self.dimension)\n for word, count in word_counts.items():","source_hash":"dee13db66543a35032a79d476fd2799e5abf482b7e58647269af148f0cf4c264","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.database.vector_store._get_word_index","uri":"program://agent-knowledge-generator/function/src.database.vector_store._get_word_index#L27-L32","kind":"function","name":"_get_word_index","path":"src/database/vector_store.py","language":"python","start_line":27,"end_line":32,"context_start_line":7,"context_end_line":52,"code":"import re\nfrom collections import Counter\n\nclass VectorStore:\n def __init__(self, config_path: str = \"config.yaml\"):\n with open(config_path, 'r') as f:\n self.config = yaml.safe_load(f)\n \n self.index = None\n self.metadata = {}\n self.dimension = 100 # Fixed dimension for our simple embeddings\n self.vocabulary = {} # Word to index mapping\n self.next_word_index = 0\n \n def _preprocess_text(self, text: str) -> List[str]:\n \"\"\"Simple text preprocessing.\"\"\"\n # Convert to lowercase and split into words\n words = re.findall(r'\\w+', text.lower())\n return words\n \n def _get_word_index(self, word: str) -> int:\n \"\"\"Get or create index for a word.\"\"\"\n if word not in self.vocabulary:\n self.vocabulary[word] = self.next_word_index\n self.next_word_index += 1\n return self.vocabulary[word]\n \n def _get_text_embedding(self, text: str) -> np.ndarray:\n \"\"\"Create a simple frequency-based embedding for text.\"\"\"\n words = self._preprocess_text(text)\n if not words:\n return np.zeros(self.dimension)\n \n # Count word frequencies\n word_counts = Counter(words)\n \n # Create embedding vector\n embedding = np.zeros(self.dimension)\n for word, count in word_counts.items():\n index = self._get_word_index(word) % self.dimension\n embedding[index] += count\n \n # Normalize the vector\n norm = np.linalg.norm(embedding)\n if norm > 0:\n embedding = embedding / norm","source_hash":"dee13db66543a35032a79d476fd2799e5abf482b7e58647269af148f0cf4c264","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.database.vector_store._get_text_embedding","uri":"program://agent-knowledge-generator/function/src.database.vector_store._get_text_embedding#L34-L54","kind":"function","name":"_get_text_embedding","path":"src/database/vector_store.py","language":"python","start_line":34,"end_line":54,"context_start_line":14,"context_end_line":74,"code":" \n self.index = None\n self.metadata = {}\n self.dimension = 100 # Fixed dimension for our simple embeddings\n self.vocabulary = {} # Word to index mapping\n self.next_word_index = 0\n \n def _preprocess_text(self, text: str) -> List[str]:\n \"\"\"Simple text preprocessing.\"\"\"\n # Convert to lowercase and split into words\n words = re.findall(r'\\w+', text.lower())\n return words\n \n def _get_word_index(self, word: str) -> int:\n \"\"\"Get or create index for a word.\"\"\"\n if word not in self.vocabulary:\n self.vocabulary[word] = self.next_word_index\n self.next_word_index += 1\n return self.vocabulary[word]\n \n def _get_text_embedding(self, text: str) -> np.ndarray:\n \"\"\"Create a simple frequency-based embedding for text.\"\"\"\n words = self._preprocess_text(text)\n if not words:\n return np.zeros(self.dimension)\n \n # Count word frequencies\n word_counts = Counter(words)\n \n # Create embedding vector\n embedding = np.zeros(self.dimension)\n for word, count in word_counts.items():\n index = self._get_word_index(word) % self.dimension\n embedding[index] += count\n \n # Normalize the vector\n norm = np.linalg.norm(embedding)\n if norm > 0:\n embedding = embedding / norm\n \n return embedding\n\n def create_index(self, index_type: str = \"flat\") -> None:\n \"\"\"Initialize FAISS index.\"\"\"\n if index_type == \"flat\":\n self.index = faiss.IndexFlatL2(self.dimension)\n elif index_type == \"hnsw\":\n self.index = faiss.IndexHNSWFlat(self.dimension, 32)\n else:\n raise ValueError(f\"Unsupported index type: {index_type}\")\n \n logger.info(f\"Created {index_type} index with dimension {self.dimension}\")\n\n def add_texts(self, texts: List[str], metadata: Optional[List[Dict]] = None) -> List[int]:\n \"\"\"Add texts to the vector store.\"\"\"\n if self.index is None:\n self.create_index()\n \n # Get embeddings for all texts\n embeddings = []\n for text in texts:","source_hash":"dee13db66543a35032a79d476fd2799e5abf482b7e58647269af148f0cf4c264","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.database.vector_store.create_index","uri":"program://agent-knowledge-generator/function/src.database.vector_store.create_index#L56-L65","kind":"function","name":"create_index","path":"src/database/vector_store.py","language":"python","start_line":56,"end_line":65,"context_start_line":36,"context_end_line":85,"code":" words = self._preprocess_text(text)\n if not words:\n return np.zeros(self.dimension)\n \n # Count word frequencies\n word_counts = Counter(words)\n \n # Create embedding vector\n embedding = np.zeros(self.dimension)\n for word, count in word_counts.items():\n index = self._get_word_index(word) % self.dimension\n embedding[index] += count\n \n # Normalize the vector\n norm = np.linalg.norm(embedding)\n if norm > 0:\n embedding = embedding / norm\n \n return embedding\n\n def create_index(self, index_type: str = \"flat\") -> None:\n \"\"\"Initialize FAISS index.\"\"\"\n if index_type == \"flat\":\n self.index = faiss.IndexFlatL2(self.dimension)\n elif index_type == \"hnsw\":\n self.index = faiss.IndexHNSWFlat(self.dimension, 32)\n else:\n raise ValueError(f\"Unsupported index type: {index_type}\")\n \n logger.info(f\"Created {index_type} index with dimension {self.dimension}\")\n\n def add_texts(self, texts: List[str], metadata: Optional[List[Dict]] = None) -> List[int]:\n \"\"\"Add texts to the vector store.\"\"\"\n if self.index is None:\n self.create_index()\n \n # Get embeddings for all texts\n embeddings = []\n for text in texts:\n embedding = self._get_text_embedding(text)\n embeddings.append(embedding)\n \n embeddings_array = np.array(embeddings).astype('float32')\n \n if metadata:\n ids = list(range(len(self.metadata), len(self.metadata) + len(texts)))\n for i, meta in zip(ids, metadata):\n self.metadata[i] = meta\n else:\n ids = list(range(len(self.metadata), len(self.metadata) + len(texts)))","source_hash":"dee13db66543a35032a79d476fd2799e5abf482b7e58647269af148f0cf4c264","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.database.vector_store.add_texts","uri":"program://agent-knowledge-generator/function/src.database.vector_store.add_texts#L67-L88","kind":"function","name":"add_texts","path":"src/database/vector_store.py","language":"python","start_line":67,"end_line":88,"context_start_line":47,"context_end_line":108,"code":" embedding[index] += count\n \n # Normalize the vector\n norm = np.linalg.norm(embedding)\n if norm > 0:\n embedding = embedding / norm\n \n return embedding\n\n def create_index(self, index_type: str = \"flat\") -> None:\n \"\"\"Initialize FAISS index.\"\"\"\n if index_type == \"flat\":\n self.index = faiss.IndexFlatL2(self.dimension)\n elif index_type == \"hnsw\":\n self.index = faiss.IndexHNSWFlat(self.dimension, 32)\n else:\n raise ValueError(f\"Unsupported index type: {index_type}\")\n \n logger.info(f\"Created {index_type} index with dimension {self.dimension}\")\n\n def add_texts(self, texts: List[str], metadata: Optional[List[Dict]] = None) -> List[int]:\n \"\"\"Add texts to the vector store.\"\"\"\n if self.index is None:\n self.create_index()\n \n # Get embeddings for all texts\n embeddings = []\n for text in texts:\n embedding = self._get_text_embedding(text)\n embeddings.append(embedding)\n \n embeddings_array = np.array(embeddings).astype('float32')\n \n if metadata:\n ids = list(range(len(self.metadata), len(self.metadata) + len(texts)))\n for i, meta in zip(ids, metadata):\n self.metadata[i] = meta\n else:\n ids = list(range(len(self.metadata), len(self.metadata) + len(texts)))\n \n self.index.add(embeddings_array)\n return ids\n\n def search(self, query: str, k: int = 5) -> List[Dict[str, Any]]:\n \"\"\"Search the vector store for similar texts.\"\"\"\n query_embedding = self._get_text_embedding(query)\n \n D, I = self.index.search(\n np.array([query_embedding]).astype('float32'), \n k\n )\n \n results = []\n for score, idx in zip(D[0], I[0]):\n result = {\n 'id': int(idx),\n 'score': float(score),\n 'metadata': self.metadata.get(int(idx), {})\n }\n results.append(result)\n \n return results ","source_hash":"dee13db66543a35032a79d476fd2799e5abf482b7e58647269af148f0cf4c264","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.database.vector_store.search","uri":"program://agent-knowledge-generator/function/src.database.vector_store.search#L90-L108","kind":"function","name":"search","path":"src/database/vector_store.py","language":"python","start_line":90,"end_line":108,"context_start_line":70,"context_end_line":108,"code":" self.create_index()\n \n # Get embeddings for all texts\n embeddings = []\n for text in texts:\n embedding = self._get_text_embedding(text)\n embeddings.append(embedding)\n \n embeddings_array = np.array(embeddings).astype('float32')\n \n if metadata:\n ids = list(range(len(self.metadata), len(self.metadata) + len(texts)))\n for i, meta in zip(ids, metadata):\n self.metadata[i] = meta\n else:\n ids = list(range(len(self.metadata), len(self.metadata) + len(texts)))\n \n self.index.add(embeddings_array)\n return ids\n\n def search(self, query: str, k: int = 5) -> List[Dict[str, Any]]:\n \"\"\"Search the vector store for similar texts.\"\"\"\n query_embedding = self._get_text_embedding(query)\n \n D, I = self.index.search(\n np.array([query_embedding]).astype('float32'), \n k\n )\n \n results = []\n for score, idx in zip(D[0], I[0]):\n result = {\n 'id': int(idx),\n 'score': float(score),\n 'metadata': self.metadata.get(int(idx), {})\n }\n results.append(result)\n \n return results ","source_hash":"dee13db66543a35032a79d476fd2799e5abf482b7e58647269af148f0cf4c264","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.utils.data_processor","uri":"program://agent-knowledge-generator/module/src.utils.data_processor#L1-L43","kind":"module","name":"src.utils.data_processor","path":"src/utils/data_processor.py","language":"python","start_line":1,"end_line":43,"context_start_line":1,"context_end_line":43,"code":"from typing import List, Dict, Any, Tuple\nimport pandas as pd\nimport json\nfrom loguru import logger\n\nclass DataProcessor:\n @staticmethod\n def process_file(file_path: str, file_format: str) -> Tuple[List[str], List[Dict]]:\n \"\"\"Process input file and return texts and metadata.\"\"\"\n try:\n if file_format == 'csv':\n return DataProcessor._process_csv(file_path)\n elif file_format == 'json':\n return DataProcessor._process_json(file_path)\n elif file_format == 'txt':\n return DataProcessor._process_txt(file_path)\n else:\n raise ValueError(f\"Unsupported file format: {file_format}\")\n except Exception as e:\n logger.error(f\"Error processing file: {e}\")\n raise\n\n @staticmethod\n def _process_csv(file_path: str) -> Tuple[List[str], List[Dict]]:\n df = pd.read_csv(file_path)\n texts = df.iloc[:, 0].tolist() # Assume first column contains text\n metadata = df.to_dict('records')\n return texts, metadata\n\n @staticmethod\n def _process_json(file_path: str) -> Tuple[List[str], List[Dict]]:\n with open(file_path, 'r') as f:\n data = json.load(f)\n texts = [item.get('text', '') for item in data]\n metadata = data\n return texts, metadata\n\n @staticmethod\n def _process_txt(file_path: str) -> Tuple[List[str], List[Dict]]:\n with open(file_path, 'r') as f:\n texts = f.readlines()\n metadata = [{'line_number': i} for i in range(len(texts))]\n return texts, metadata ","source_hash":"fdcf1488a59ab6c2de0381162fcb49b4fd1598c70f2bc161084ca77755f17953","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.utils.data_processor.DataProcessor","uri":"program://agent-knowledge-generator/class/src.utils.data_processor.DataProcessor#L6-L43","kind":"class","name":"DataProcessor","path":"src/utils/data_processor.py","language":"python","start_line":6,"end_line":43,"context_start_line":1,"context_end_line":43,"code":"from typing import List, Dict, Any, Tuple\nimport pandas as pd\nimport json\nfrom loguru import logger\n\nclass DataProcessor:\n @staticmethod\n def process_file(file_path: str, file_format: str) -> Tuple[List[str], List[Dict]]:\n \"\"\"Process input file and return texts and metadata.\"\"\"\n try:\n if file_format == 'csv':\n return DataProcessor._process_csv(file_path)\n elif file_format == 'json':\n return DataProcessor._process_json(file_path)\n elif file_format == 'txt':\n return DataProcessor._process_txt(file_path)\n else:\n raise ValueError(f\"Unsupported file format: {file_format}\")\n except Exception as e:\n logger.error(f\"Error processing file: {e}\")\n raise\n\n @staticmethod\n def _process_csv(file_path: str) -> Tuple[List[str], List[Dict]]:\n df = pd.read_csv(file_path)\n texts = df.iloc[:, 0].tolist() # Assume first column contains text\n metadata = df.to_dict('records')\n return texts, metadata\n\n @staticmethod\n def _process_json(file_path: str) -> Tuple[List[str], List[Dict]]:\n with open(file_path, 'r') as f:\n data = json.load(f)\n texts = [item.get('text', '') for item in data]\n metadata = data\n return texts, metadata\n\n @staticmethod\n def _process_txt(file_path: str) -> Tuple[List[str], List[Dict]]:\n with open(file_path, 'r') as f:\n texts = f.readlines()\n metadata = [{'line_number': i} for i in range(len(texts))]\n return texts, metadata ","source_hash":"fdcf1488a59ab6c2de0381162fcb49b4fd1598c70f2bc161084ca77755f17953","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.utils.data_processor.process_file","uri":"program://agent-knowledge-generator/function/src.utils.data_processor.process_file#L8-L21","kind":"function","name":"process_file","path":"src/utils/data_processor.py","language":"python","start_line":8,"end_line":21,"context_start_line":1,"context_end_line":41,"code":"from typing import List, Dict, Any, Tuple\nimport pandas as pd\nimport json\nfrom loguru import logger\n\nclass DataProcessor:\n @staticmethod\n def process_file(file_path: str, file_format: str) -> Tuple[List[str], List[Dict]]:\n \"\"\"Process input file and return texts and metadata.\"\"\"\n try:\n if file_format == 'csv':\n return DataProcessor._process_csv(file_path)\n elif file_format == 'json':\n return DataProcessor._process_json(file_path)\n elif file_format == 'txt':\n return DataProcessor._process_txt(file_path)\n else:\n raise ValueError(f\"Unsupported file format: {file_format}\")\n except Exception as e:\n logger.error(f\"Error processing file: {e}\")\n raise\n\n @staticmethod\n def _process_csv(file_path: str) -> Tuple[List[str], List[Dict]]:\n df = pd.read_csv(file_path)\n texts = df.iloc[:, 0].tolist() # Assume first column contains text\n metadata = df.to_dict('records')\n return texts, metadata\n\n @staticmethod\n def _process_json(file_path: str) -> Tuple[List[str], List[Dict]]:\n with open(file_path, 'r') as f:\n data = json.load(f)\n texts = [item.get('text', '') for item in data]\n metadata = data\n return texts, metadata\n\n @staticmethod\n def _process_txt(file_path: str) -> Tuple[List[str], List[Dict]]:\n with open(file_path, 'r') as f:\n texts = f.readlines()","source_hash":"fdcf1488a59ab6c2de0381162fcb49b4fd1598c70f2bc161084ca77755f17953","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.utils.data_processor._process_csv","uri":"program://agent-knowledge-generator/function/src.utils.data_processor._process_csv#L24-L28","kind":"function","name":"_process_csv","path":"src/utils/data_processor.py","language":"python","start_line":24,"end_line":28,"context_start_line":4,"context_end_line":43,"code":"from loguru import logger\n\nclass DataProcessor:\n @staticmethod\n def process_file(file_path: str, file_format: str) -> Tuple[List[str], List[Dict]]:\n \"\"\"Process input file and return texts and metadata.\"\"\"\n try:\n if file_format == 'csv':\n return DataProcessor._process_csv(file_path)\n elif file_format == 'json':\n return DataProcessor._process_json(file_path)\n elif file_format == 'txt':\n return DataProcessor._process_txt(file_path)\n else:\n raise ValueError(f\"Unsupported file format: {file_format}\")\n except Exception as e:\n logger.error(f\"Error processing file: {e}\")\n raise\n\n @staticmethod\n def _process_csv(file_path: str) -> Tuple[List[str], List[Dict]]:\n df = pd.read_csv(file_path)\n texts = df.iloc[:, 0].tolist() # Assume first column contains text\n metadata = df.to_dict('records')\n return texts, metadata\n\n @staticmethod\n def _process_json(file_path: str) -> Tuple[List[str], List[Dict]]:\n with open(file_path, 'r') as f:\n data = json.load(f)\n texts = [item.get('text', '') for item in data]\n metadata = data\n return texts, metadata\n\n @staticmethod\n def _process_txt(file_path: str) -> Tuple[List[str], List[Dict]]:\n with open(file_path, 'r') as f:\n texts = f.readlines()\n metadata = [{'line_number': i} for i in range(len(texts))]\n return texts, metadata ","source_hash":"fdcf1488a59ab6c2de0381162fcb49b4fd1598c70f2bc161084ca77755f17953","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.utils.data_processor._process_json","uri":"program://agent-knowledge-generator/function/src.utils.data_processor._process_json#L31-L36","kind":"function","name":"_process_json","path":"src/utils/data_processor.py","language":"python","start_line":31,"end_line":36,"context_start_line":11,"context_end_line":43,"code":" if file_format == 'csv':\n return DataProcessor._process_csv(file_path)\n elif file_format == 'json':\n return DataProcessor._process_json(file_path)\n elif file_format == 'txt':\n return DataProcessor._process_txt(file_path)\n else:\n raise ValueError(f\"Unsupported file format: {file_format}\")\n except Exception as e:\n logger.error(f\"Error processing file: {e}\")\n raise\n\n @staticmethod\n def _process_csv(file_path: str) -> Tuple[List[str], List[Dict]]:\n df = pd.read_csv(file_path)\n texts = df.iloc[:, 0].tolist() # Assume first column contains text\n metadata = df.to_dict('records')\n return texts, metadata\n\n @staticmethod\n def _process_json(file_path: str) -> Tuple[List[str], List[Dict]]:\n with open(file_path, 'r') as f:\n data = json.load(f)\n texts = [item.get('text', '') for item in data]\n metadata = data\n return texts, metadata\n\n @staticmethod\n def _process_txt(file_path: str) -> Tuple[List[str], List[Dict]]:\n with open(file_path, 'r') as f:\n texts = f.readlines()\n metadata = [{'line_number': i} for i in range(len(texts))]\n return texts, metadata ","source_hash":"fdcf1488a59ab6c2de0381162fcb49b4fd1598c70f2bc161084ca77755f17953","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.utils.data_processor._process_txt","uri":"program://agent-knowledge-generator/function/src.utils.data_processor._process_txt#L39-L43","kind":"function","name":"_process_txt","path":"src/utils/data_processor.py","language":"python","start_line":39,"end_line":43,"context_start_line":19,"context_end_line":43,"code":" except Exception as e:\n logger.error(f\"Error processing file: {e}\")\n raise\n\n @staticmethod\n def _process_csv(file_path: str) -> Tuple[List[str], List[Dict]]:\n df = pd.read_csv(file_path)\n texts = df.iloc[:, 0].tolist() # Assume first column contains text\n metadata = df.to_dict('records')\n return texts, metadata\n\n @staticmethod\n def _process_json(file_path: str) -> Tuple[List[str], List[Dict]]:\n with open(file_path, 'r') as f:\n data = json.load(f)\n texts = [item.get('text', '') for item in data]\n metadata = data\n return texts, metadata\n\n @staticmethod\n def _process_txt(file_path: str) -> Tuple[List[str], List[Dict]]:\n with open(file_path, 'r') as f:\n texts = f.readlines()\n metadata = [{'line_number': i} for i in range(len(texts))]\n return texts, metadata ","source_hash":"fdcf1488a59ab6c2de0381162fcb49b4fd1598c70f2bc161084ca77755f17953","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.utils.logger","uri":"program://agent-knowledge-generator/module/src.utils.logger#L1-L63","kind":"module","name":"src.utils.logger","path":"src/utils/logger.py","language":"python","start_line":1,"end_line":63,"context_start_line":1,"context_end_line":63,"code":"import json\nfrom datetime import datetime\nfrom typing import Any, Dict, Optional\nimport os\nfrom pathlib import Path\n\nclass SystemLogger:\n def __init__(self, actions_log_path: str = \"actions.log\", thoughts_log_path: str = \"thoughts.log\"):\n \"\"\"Initialize the system logger.\"\"\"\n self.actions_log_path = actions_log_path\n self.thoughts_log_path = thoughts_log_path\n self._ensure_log_files_exist()\n \n def _ensure_log_files_exist(self):\n \"\"\"Ensure log files exist and create them if they don't.\"\"\"\n for path in [self.actions_log_path, self.thoughts_log_path]:\n Path(path).touch(exist_ok=True)\n \n def _format_log_entry(self, entry_type: str, message: str, metadata: Optional[Dict[str, Any]] = None) -> str:\n \"\"\"Format a log entry as JSON.\"\"\"\n log_entry = {\n \"timestamp\": datetime.utcnow().isoformat(),\n \"type\": entry_type,\n \"message\": message\n }\n if metadata:\n log_entry[\"metadata\"] = metadata\n return json.dumps(log_entry)\n \n def log_action(self, action: str, metadata: Optional[Dict[str, Any]] = None):\n \"\"\"Log an action with optional metadata.\"\"\"\n log_entry = self._format_log_entry(\"action\", action, metadata)\n with open(self.actions_log_path, \"a\", encoding=\"utf-8\") as f:\n f.write(f\"{log_entry}\\n\")\n \n def log_thought(self, thought: str, metadata: Optional[Dict[str, Any]] = None):\n \"\"\"Log a thought process with optional metadata.\"\"\"\n log_entry = self._format_log_entry(\"thought\", thought, metadata)\n with open(self.thoughts_log_path, \"a\", encoding=\"utf-8\") as f:\n f.write(f\"{log_entry}\\n\")\n \n def get_recent_actions(self, limit: int = 10) -> list:\n \"\"\"Get the most recent actions from the log.\"\"\"\n return self._get_recent_entries(self.actions_log_path, limit)\n \n def get_recent_thoughts(self, limit: int = 10) -> list:\n \"\"\"Get the most recent thoughts from the log.\"\"\"\n return self._get_recent_entries(self.thoughts_log_path, limit)\n \n def _get_recent_entries(self, log_path: str, limit: int) -> list:\n \"\"\"Get recent entries from a log file.\"\"\"\n entries = []\n try:\n with open(log_path, \"r\", encoding=\"utf-8\") as f:\n lines = f.readlines()\n for line in lines[-limit:]:\n try:\n entries.append(json.loads(line.strip()))\n except json.JSONDecodeError:\n continue\n except FileNotFoundError:\n pass\n return entries ","source_hash":"f7967623f0de2be44890fd63622d6700c1ade5cf9dab2905cfd67fcc0df40db8","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.utils.logger.SystemLogger","uri":"program://agent-knowledge-generator/class/src.utils.logger.SystemLogger#L7-L63","kind":"class","name":"SystemLogger","path":"src/utils/logger.py","language":"python","start_line":7,"end_line":63,"context_start_line":1,"context_end_line":63,"code":"import json\nfrom datetime import datetime\nfrom typing import Any, Dict, Optional\nimport os\nfrom pathlib import Path\n\nclass SystemLogger:\n def __init__(self, actions_log_path: str = \"actions.log\", thoughts_log_path: str = \"thoughts.log\"):\n \"\"\"Initialize the system logger.\"\"\"\n self.actions_log_path = actions_log_path\n self.thoughts_log_path = thoughts_log_path\n self._ensure_log_files_exist()\n \n def _ensure_log_files_exist(self):\n \"\"\"Ensure log files exist and create them if they don't.\"\"\"\n for path in [self.actions_log_path, self.thoughts_log_path]:\n Path(path).touch(exist_ok=True)\n \n def _format_log_entry(self, entry_type: str, message: str, metadata: Optional[Dict[str, Any]] = None) -> str:\n \"\"\"Format a log entry as JSON.\"\"\"\n log_entry = {\n \"timestamp\": datetime.utcnow().isoformat(),\n \"type\": entry_type,\n \"message\": message\n }\n if metadata:\n log_entry[\"metadata\"] = metadata\n return json.dumps(log_entry)\n \n def log_action(self, action: str, metadata: Optional[Dict[str, Any]] = None):\n \"\"\"Log an action with optional metadata.\"\"\"\n log_entry = self._format_log_entry(\"action\", action, metadata)\n with open(self.actions_log_path, \"a\", encoding=\"utf-8\") as f:\n f.write(f\"{log_entry}\\n\")\n \n def log_thought(self, thought: str, metadata: Optional[Dict[str, Any]] = None):\n \"\"\"Log a thought process with optional metadata.\"\"\"\n log_entry = self._format_log_entry(\"thought\", thought, metadata)\n with open(self.thoughts_log_path, \"a\", encoding=\"utf-8\") as f:\n f.write(f\"{log_entry}\\n\")\n \n def get_recent_actions(self, limit: int = 10) -> list:\n \"\"\"Get the most recent actions from the log.\"\"\"\n return self._get_recent_entries(self.actions_log_path, limit)\n \n def get_recent_thoughts(self, limit: int = 10) -> list:\n \"\"\"Get the most recent thoughts from the log.\"\"\"\n return self._get_recent_entries(self.thoughts_log_path, limit)\n \n def _get_recent_entries(self, log_path: str, limit: int) -> list:\n \"\"\"Get recent entries from a log file.\"\"\"\n entries = []\n try:\n with open(log_path, \"r\", encoding=\"utf-8\") as f:\n lines = f.readlines()\n for line in lines[-limit:]:\n try:\n entries.append(json.loads(line.strip()))\n except json.JSONDecodeError:\n continue\n except FileNotFoundError:\n pass\n return entries ","source_hash":"f7967623f0de2be44890fd63622d6700c1ade5cf9dab2905cfd67fcc0df40db8","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.utils.logger.__init__","uri":"program://agent-knowledge-generator/function/src.utils.logger.__init__#L8-L12","kind":"function","name":"__init__","path":"src/utils/logger.py","language":"python","start_line":8,"end_line":12,"context_start_line":1,"context_end_line":32,"code":"import json\nfrom datetime import datetime\nfrom typing import Any, Dict, Optional\nimport os\nfrom pathlib import Path\n\nclass SystemLogger:\n def __init__(self, actions_log_path: str = \"actions.log\", thoughts_log_path: str = \"thoughts.log\"):\n \"\"\"Initialize the system logger.\"\"\"\n self.actions_log_path = actions_log_path\n self.thoughts_log_path = thoughts_log_path\n self._ensure_log_files_exist()\n \n def _ensure_log_files_exist(self):\n \"\"\"Ensure log files exist and create them if they don't.\"\"\"\n for path in [self.actions_log_path, self.thoughts_log_path]:\n Path(path).touch(exist_ok=True)\n \n def _format_log_entry(self, entry_type: str, message: str, metadata: Optional[Dict[str, Any]] = None) -> str:\n \"\"\"Format a log entry as JSON.\"\"\"\n log_entry = {\n \"timestamp\": datetime.utcnow().isoformat(),\n \"type\": entry_type,\n \"message\": message\n }\n if metadata:\n log_entry[\"metadata\"] = metadata\n return json.dumps(log_entry)\n \n def log_action(self, action: str, metadata: Optional[Dict[str, Any]] = None):\n \"\"\"Log an action with optional metadata.\"\"\"\n log_entry = self._format_log_entry(\"action\", action, metadata)","source_hash":"f7967623f0de2be44890fd63622d6700c1ade5cf9dab2905cfd67fcc0df40db8","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.utils.logger._ensure_log_files_exist","uri":"program://agent-knowledge-generator/function/src.utils.logger._ensure_log_files_exist#L14-L17","kind":"function","name":"_ensure_log_files_exist","path":"src/utils/logger.py","language":"python","start_line":14,"end_line":17,"context_start_line":1,"context_end_line":37,"code":"import json\nfrom datetime import datetime\nfrom typing import Any, Dict, Optional\nimport os\nfrom pathlib import Path\n\nclass SystemLogger:\n def __init__(self, actions_log_path: str = \"actions.log\", thoughts_log_path: str = \"thoughts.log\"):\n \"\"\"Initialize the system logger.\"\"\"\n self.actions_log_path = actions_log_path\n self.thoughts_log_path = thoughts_log_path\n self._ensure_log_files_exist()\n \n def _ensure_log_files_exist(self):\n \"\"\"Ensure log files exist and create them if they don't.\"\"\"\n for path in [self.actions_log_path, self.thoughts_log_path]:\n Path(path).touch(exist_ok=True)\n \n def _format_log_entry(self, entry_type: str, message: str, metadata: Optional[Dict[str, Any]] = None) -> str:\n \"\"\"Format a log entry as JSON.\"\"\"\n log_entry = {\n \"timestamp\": datetime.utcnow().isoformat(),\n \"type\": entry_type,\n \"message\": message\n }\n if metadata:\n log_entry[\"metadata\"] = metadata\n return json.dumps(log_entry)\n \n def log_action(self, action: str, metadata: Optional[Dict[str, Any]] = None):\n \"\"\"Log an action with optional metadata.\"\"\"\n log_entry = self._format_log_entry(\"action\", action, metadata)\n with open(self.actions_log_path, \"a\", encoding=\"utf-8\") as f:\n f.write(f\"{log_entry}\\n\")\n \n def log_thought(self, thought: str, metadata: Optional[Dict[str, Any]] = None):\n \"\"\"Log a thought process with optional metadata.\"\"\"","source_hash":"f7967623f0de2be44890fd63622d6700c1ade5cf9dab2905cfd67fcc0df40db8","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.utils.logger._format_log_entry","uri":"program://agent-knowledge-generator/function/src.utils.logger._format_log_entry#L19-L28","kind":"function","name":"_format_log_entry","path":"src/utils/logger.py","language":"python","start_line":19,"end_line":28,"context_start_line":1,"context_end_line":48,"code":"import json\nfrom datetime import datetime\nfrom typing import Any, Dict, Optional\nimport os\nfrom pathlib import Path\n\nclass SystemLogger:\n def __init__(self, actions_log_path: str = \"actions.log\", thoughts_log_path: str = \"thoughts.log\"):\n \"\"\"Initialize the system logger.\"\"\"\n self.actions_log_path = actions_log_path\n self.thoughts_log_path = thoughts_log_path\n self._ensure_log_files_exist()\n \n def _ensure_log_files_exist(self):\n \"\"\"Ensure log files exist and create them if they don't.\"\"\"\n for path in [self.actions_log_path, self.thoughts_log_path]:\n Path(path).touch(exist_ok=True)\n \n def _format_log_entry(self, entry_type: str, message: str, metadata: Optional[Dict[str, Any]] = None) -> str:\n \"\"\"Format a log entry as JSON.\"\"\"\n log_entry = {\n \"timestamp\": datetime.utcnow().isoformat(),\n \"type\": entry_type,\n \"message\": message\n }\n if metadata:\n log_entry[\"metadata\"] = metadata\n return json.dumps(log_entry)\n \n def log_action(self, action: str, metadata: Optional[Dict[str, Any]] = None):\n \"\"\"Log an action with optional metadata.\"\"\"\n log_entry = self._format_log_entry(\"action\", action, metadata)\n with open(self.actions_log_path, \"a\", encoding=\"utf-8\") as f:\n f.write(f\"{log_entry}\\n\")\n \n def log_thought(self, thought: str, metadata: Optional[Dict[str, Any]] = None):\n \"\"\"Log a thought process with optional metadata.\"\"\"\n log_entry = self._format_log_entry(\"thought\", thought, metadata)\n with open(self.thoughts_log_path, \"a\", encoding=\"utf-8\") as f:\n f.write(f\"{log_entry}\\n\")\n \n def get_recent_actions(self, limit: int = 10) -> list:\n \"\"\"Get the most recent actions from the log.\"\"\"\n return self._get_recent_entries(self.actions_log_path, limit)\n \n def get_recent_thoughts(self, limit: int = 10) -> list:\n \"\"\"Get the most recent thoughts from the log.\"\"\"\n return self._get_recent_entries(self.thoughts_log_path, limit)","source_hash":"f7967623f0de2be44890fd63622d6700c1ade5cf9dab2905cfd67fcc0df40db8","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.utils.logger.log_action","uri":"program://agent-knowledge-generator/function/src.utils.logger.log_action#L30-L34","kind":"function","name":"log_action","path":"src/utils/logger.py","language":"python","start_line":30,"end_line":34,"context_start_line":10,"context_end_line":54,"code":" self.actions_log_path = actions_log_path\n self.thoughts_log_path = thoughts_log_path\n self._ensure_log_files_exist()\n \n def _ensure_log_files_exist(self):\n \"\"\"Ensure log files exist and create them if they don't.\"\"\"\n for path in [self.actions_log_path, self.thoughts_log_path]:\n Path(path).touch(exist_ok=True)\n \n def _format_log_entry(self, entry_type: str, message: str, metadata: Optional[Dict[str, Any]] = None) -> str:\n \"\"\"Format a log entry as JSON.\"\"\"\n log_entry = {\n \"timestamp\": datetime.utcnow().isoformat(),\n \"type\": entry_type,\n \"message\": message\n }\n if metadata:\n log_entry[\"metadata\"] = metadata\n return json.dumps(log_entry)\n \n def log_action(self, action: str, metadata: Optional[Dict[str, Any]] = None):\n \"\"\"Log an action with optional metadata.\"\"\"\n log_entry = self._format_log_entry(\"action\", action, metadata)\n with open(self.actions_log_path, \"a\", encoding=\"utf-8\") as f:\n f.write(f\"{log_entry}\\n\")\n \n def log_thought(self, thought: str, metadata: Optional[Dict[str, Any]] = None):\n \"\"\"Log a thought process with optional metadata.\"\"\"\n log_entry = self._format_log_entry(\"thought\", thought, metadata)\n with open(self.thoughts_log_path, \"a\", encoding=\"utf-8\") as f:\n f.write(f\"{log_entry}\\n\")\n \n def get_recent_actions(self, limit: int = 10) -> list:\n \"\"\"Get the most recent actions from the log.\"\"\"\n return self._get_recent_entries(self.actions_log_path, limit)\n \n def get_recent_thoughts(self, limit: int = 10) -> list:\n \"\"\"Get the most recent thoughts from the log.\"\"\"\n return self._get_recent_entries(self.thoughts_log_path, limit)\n \n def _get_recent_entries(self, log_path: str, limit: int) -> list:\n \"\"\"Get recent entries from a log file.\"\"\"\n entries = []\n try:\n with open(log_path, \"r\", encoding=\"utf-8\") as f:","source_hash":"f7967623f0de2be44890fd63622d6700c1ade5cf9dab2905cfd67fcc0df40db8","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.utils.logger.log_thought","uri":"program://agent-knowledge-generator/function/src.utils.logger.log_thought#L36-L40","kind":"function","name":"log_thought","path":"src/utils/logger.py","language":"python","start_line":36,"end_line":40,"context_start_line":16,"context_end_line":60,"code":" for path in [self.actions_log_path, self.thoughts_log_path]:\n Path(path).touch(exist_ok=True)\n \n def _format_log_entry(self, entry_type: str, message: str, metadata: Optional[Dict[str, Any]] = None) -> str:\n \"\"\"Format a log entry as JSON.\"\"\"\n log_entry = {\n \"timestamp\": datetime.utcnow().isoformat(),\n \"type\": entry_type,\n \"message\": message\n }\n if metadata:\n log_entry[\"metadata\"] = metadata\n return json.dumps(log_entry)\n \n def log_action(self, action: str, metadata: Optional[Dict[str, Any]] = None):\n \"\"\"Log an action with optional metadata.\"\"\"\n log_entry = self._format_log_entry(\"action\", action, metadata)\n with open(self.actions_log_path, \"a\", encoding=\"utf-8\") as f:\n f.write(f\"{log_entry}\\n\")\n \n def log_thought(self, thought: str, metadata: Optional[Dict[str, Any]] = None):\n \"\"\"Log a thought process with optional metadata.\"\"\"\n log_entry = self._format_log_entry(\"thought\", thought, metadata)\n with open(self.thoughts_log_path, \"a\", encoding=\"utf-8\") as f:\n f.write(f\"{log_entry}\\n\")\n \n def get_recent_actions(self, limit: int = 10) -> list:\n \"\"\"Get the most recent actions from the log.\"\"\"\n return self._get_recent_entries(self.actions_log_path, limit)\n \n def get_recent_thoughts(self, limit: int = 10) -> list:\n \"\"\"Get the most recent thoughts from the log.\"\"\"\n return self._get_recent_entries(self.thoughts_log_path, limit)\n \n def _get_recent_entries(self, log_path: str, limit: int) -> list:\n \"\"\"Get recent entries from a log file.\"\"\"\n entries = []\n try:\n with open(log_path, \"r\", encoding=\"utf-8\") as f:\n lines = f.readlines()\n for line in lines[-limit:]:\n try:\n entries.append(json.loads(line.strip()))\n except json.JSONDecodeError:\n continue","source_hash":"f7967623f0de2be44890fd63622d6700c1ade5cf9dab2905cfd67fcc0df40db8","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.utils.logger.get_recent_actions","uri":"program://agent-knowledge-generator/function/src.utils.logger.get_recent_actions#L42-L44","kind":"function","name":"get_recent_actions","path":"src/utils/logger.py","language":"python","start_line":42,"end_line":44,"context_start_line":22,"context_end_line":63,"code":" \"timestamp\": datetime.utcnow().isoformat(),\n \"type\": entry_type,\n \"message\": message\n }\n if metadata:\n log_entry[\"metadata\"] = metadata\n return json.dumps(log_entry)\n \n def log_action(self, action: str, metadata: Optional[Dict[str, Any]] = None):\n \"\"\"Log an action with optional metadata.\"\"\"\n log_entry = self._format_log_entry(\"action\", action, metadata)\n with open(self.actions_log_path, \"a\", encoding=\"utf-8\") as f:\n f.write(f\"{log_entry}\\n\")\n \n def log_thought(self, thought: str, metadata: Optional[Dict[str, Any]] = None):\n \"\"\"Log a thought process with optional metadata.\"\"\"\n log_entry = self._format_log_entry(\"thought\", thought, metadata)\n with open(self.thoughts_log_path, \"a\", encoding=\"utf-8\") as f:\n f.write(f\"{log_entry}\\n\")\n \n def get_recent_actions(self, limit: int = 10) -> list:\n \"\"\"Get the most recent actions from the log.\"\"\"\n return self._get_recent_entries(self.actions_log_path, limit)\n \n def get_recent_thoughts(self, limit: int = 10) -> list:\n \"\"\"Get the most recent thoughts from the log.\"\"\"\n return self._get_recent_entries(self.thoughts_log_path, limit)\n \n def _get_recent_entries(self, log_path: str, limit: int) -> list:\n \"\"\"Get recent entries from a log file.\"\"\"\n entries = []\n try:\n with open(log_path, \"r\", encoding=\"utf-8\") as f:\n lines = f.readlines()\n for line in lines[-limit:]:\n try:\n entries.append(json.loads(line.strip()))\n except json.JSONDecodeError:\n continue\n except FileNotFoundError:\n pass\n return entries ","source_hash":"f7967623f0de2be44890fd63622d6700c1ade5cf9dab2905cfd67fcc0df40db8","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.utils.logger.get_recent_thoughts","uri":"program://agent-knowledge-generator/function/src.utils.logger.get_recent_thoughts#L46-L48","kind":"function","name":"get_recent_thoughts","path":"src/utils/logger.py","language":"python","start_line":46,"end_line":48,"context_start_line":26,"context_end_line":63,"code":" if metadata:\n log_entry[\"metadata\"] = metadata\n return json.dumps(log_entry)\n \n def log_action(self, action: str, metadata: Optional[Dict[str, Any]] = None):\n \"\"\"Log an action with optional metadata.\"\"\"\n log_entry = self._format_log_entry(\"action\", action, metadata)\n with open(self.actions_log_path, \"a\", encoding=\"utf-8\") as f:\n f.write(f\"{log_entry}\\n\")\n \n def log_thought(self, thought: str, metadata: Optional[Dict[str, Any]] = None):\n \"\"\"Log a thought process with optional metadata.\"\"\"\n log_entry = self._format_log_entry(\"thought\", thought, metadata)\n with open(self.thoughts_log_path, \"a\", encoding=\"utf-8\") as f:\n f.write(f\"{log_entry}\\n\")\n \n def get_recent_actions(self, limit: int = 10) -> list:\n \"\"\"Get the most recent actions from the log.\"\"\"\n return self._get_recent_entries(self.actions_log_path, limit)\n \n def get_recent_thoughts(self, limit: int = 10) -> list:\n \"\"\"Get the most recent thoughts from the log.\"\"\"\n return self._get_recent_entries(self.thoughts_log_path, limit)\n \n def _get_recent_entries(self, log_path: str, limit: int) -> list:\n \"\"\"Get recent entries from a log file.\"\"\"\n entries = []\n try:\n with open(log_path, \"r\", encoding=\"utf-8\") as f:\n lines = f.readlines()\n for line in lines[-limit:]:\n try:\n entries.append(json.loads(line.strip()))\n except json.JSONDecodeError:\n continue\n except FileNotFoundError:\n pass\n return entries ","source_hash":"f7967623f0de2be44890fd63622d6700c1ade5cf9dab2905cfd67fcc0df40db8","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.utils.logger._get_recent_entries","uri":"program://agent-knowledge-generator/function/src.utils.logger._get_recent_entries#L50-L63","kind":"function","name":"_get_recent_entries","path":"src/utils/logger.py","language":"python","start_line":50,"end_line":63,"context_start_line":30,"context_end_line":63,"code":" def log_action(self, action: str, metadata: Optional[Dict[str, Any]] = None):\n \"\"\"Log an action with optional metadata.\"\"\"\n log_entry = self._format_log_entry(\"action\", action, metadata)\n with open(self.actions_log_path, \"a\", encoding=\"utf-8\") as f:\n f.write(f\"{log_entry}\\n\")\n \n def log_thought(self, thought: str, metadata: Optional[Dict[str, Any]] = None):\n \"\"\"Log a thought process with optional metadata.\"\"\"\n log_entry = self._format_log_entry(\"thought\", thought, metadata)\n with open(self.thoughts_log_path, \"a\", encoding=\"utf-8\") as f:\n f.write(f\"{log_entry}\\n\")\n \n def get_recent_actions(self, limit: int = 10) -> list:\n \"\"\"Get the most recent actions from the log.\"\"\"\n return self._get_recent_entries(self.actions_log_path, limit)\n \n def get_recent_thoughts(self, limit: int = 10) -> list:\n \"\"\"Get the most recent thoughts from the log.\"\"\"\n return self._get_recent_entries(self.thoughts_log_path, limit)\n \n def _get_recent_entries(self, log_path: str, limit: int) -> list:\n \"\"\"Get recent entries from a log file.\"\"\"\n entries = []\n try:\n with open(log_path, \"r\", encoding=\"utf-8\") as f:\n lines = f.readlines()\n for line in lines[-limit:]:\n try:\n entries.append(json.loads(line.strip()))\n except json.JSONDecodeError:\n continue\n except FileNotFoundError:\n pass\n return entries ","source_hash":"f7967623f0de2be44890fd63622d6700c1ade5cf9dab2905cfd67fcc0df40db8","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.api.main","uri":"program://agent-knowledge-generator/module/src.api.main#L1-L99","kind":"module","name":"src.api.main","path":"src/api/main.py","language":"python","start_line":1,"end_line":99,"context_start_line":1,"context_end_line":99,"code":"from fastapi import FastAPI, UploadFile, HTTPException\nfrom fastapi.middleware.cors import CORSMiddleware\nfrom pydantic import BaseModel, Field\nfrom typing import List, Optional, Dict\nimport yaml\nfrom loguru import logger\nimport sys\nimport os\nfrom dotenv import load_dotenv\n\n# Load environment variables\nload_dotenv()\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nfrom database.vector_store import VectorStore\nfrom chatgpt.knowledge_processor import KnowledgeProcessor\n\napp = FastAPI(title=\"RAG Vector Database API\")\n\n# CORS middleware\napp.add_middleware(\n CORSMiddleware,\n allow_origins=[\"*\"],\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\n# Load configuration\nwith open(\"config.yaml\", 'r') as f:\n config = yaml.safe_load(f)\n\n# Initialize vector store and knowledge processor\nvector_store = VectorStore()\nknowledge_processor = KnowledgeProcessor(api_key=os.getenv('OPENAI_API_KEY'))\n\nclass QueryRequest(BaseModel):\n query: str\n k: int = Field(default=5, gt=0, description=\"Number of results to return\")\n\nclass AddTextsRequest(BaseModel):\n texts: List[str]\n metadata: Optional[List[Dict]] = None\n\nclass GenerateKnowledgeRequest(BaseModel):\n user_input: str\n\n@app.post(\"/generate-knowledge\")\nasync def generate_knowledge(request: GenerateKnowledgeRequest):\n \"\"\"Generate agent knowledge from user input and store it in the vector database.\"\"\"\n try:\n # Process user input to generate knowledge\n knowledge = knowledge_processor.process_user_input(request.user_input)\n \n # Store the generated knowledge in vector database\n ids = vector_store.add_texts(\n texts=knowledge[\"text_chunks\"],\n metadata=knowledge[\"metadata\"]\n )\n \n return {\n \"message\": \"Successfully generated and stored agent knowledge\",\n \"structured_knowledge\": knowledge[\"structured_knowledge\"],\n \"vector_ids\": ids\n }\n except Exception as e:\n logger.error(f\"Knowledge generation error: {e}\")\n raise HTTPException(status_code=500, detail=str(e))\n\n@app.post(\"/search\")\nasync def search(request: QueryRequest):\n try:\n results = vector_store.search(request.query, k=request.k)\n return {\"results\": results}\n except Exception as e:\n logger.error(f\"Search error: {e}\")\n raise HTTPException(status_code=500, detail=str(e))\n\n@app.post(\"/add-texts\")\nasync def add_texts(request: AddTextsRequest):\n try:\n ids = vector_store.add_texts(request.texts, request.metadata)\n return {\"ids\": ids}\n except Exception as e:\n logger.error(f\"Add texts error: {e}\")\n raise HTTPException(status_code=500, detail=str(e))\n\n@app.get(\"/health\")\nasync def health_check():\n return {\"status\": \"healthy\"}\n\nif __name__ == \"__main__\":\n import uvicorn\n uvicorn.run(\n \"main:app\",\n host=config['api']['host'],\n port=config['api']['port'],\n reload=True\n ) ","source_hash":"85bcb196f52273b2dcef31794d490e2aa848062da63103c1d8b0b80db9560ff6","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.api.main.QueryRequest","uri":"program://agent-knowledge-generator/class/src.api.main.QueryRequest#L37-L39","kind":"class","name":"QueryRequest","path":"src/api/main.py","language":"python","start_line":37,"end_line":39,"context_start_line":17,"context_end_line":59,"code":"\napp = FastAPI(title=\"RAG Vector Database API\")\n\n# CORS middleware\napp.add_middleware(\n CORSMiddleware,\n allow_origins=[\"*\"],\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\n# Load configuration\nwith open(\"config.yaml\", 'r') as f:\n config = yaml.safe_load(f)\n\n# Initialize vector store and knowledge processor\nvector_store = VectorStore()\nknowledge_processor = KnowledgeProcessor(api_key=os.getenv('OPENAI_API_KEY'))\n\nclass QueryRequest(BaseModel):\n query: str\n k: int = Field(default=5, gt=0, description=\"Number of results to return\")\n\nclass AddTextsRequest(BaseModel):\n texts: List[str]\n metadata: Optional[List[Dict]] = None\n\nclass GenerateKnowledgeRequest(BaseModel):\n user_input: str\n\n@app.post(\"/generate-knowledge\")\nasync def generate_knowledge(request: GenerateKnowledgeRequest):\n \"\"\"Generate agent knowledge from user input and store it in the vector database.\"\"\"\n try:\n # Process user input to generate knowledge\n knowledge = knowledge_processor.process_user_input(request.user_input)\n \n # Store the generated knowledge in vector database\n ids = vector_store.add_texts(\n texts=knowledge[\"text_chunks\"],\n metadata=knowledge[\"metadata\"]\n )","source_hash":"85bcb196f52273b2dcef31794d490e2aa848062da63103c1d8b0b80db9560ff6","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.api.main.AddTextsRequest","uri":"program://agent-knowledge-generator/class/src.api.main.AddTextsRequest#L41-L43","kind":"class","name":"AddTextsRequest","path":"src/api/main.py","language":"python","start_line":41,"end_line":43,"context_start_line":21,"context_end_line":63,"code":"app.add_middleware(\n CORSMiddleware,\n allow_origins=[\"*\"],\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\n# Load configuration\nwith open(\"config.yaml\", 'r') as f:\n config = yaml.safe_load(f)\n\n# Initialize vector store and knowledge processor\nvector_store = VectorStore()\nknowledge_processor = KnowledgeProcessor(api_key=os.getenv('OPENAI_API_KEY'))\n\nclass QueryRequest(BaseModel):\n query: str\n k: int = Field(default=5, gt=0, description=\"Number of results to return\")\n\nclass AddTextsRequest(BaseModel):\n texts: List[str]\n metadata: Optional[List[Dict]] = None\n\nclass GenerateKnowledgeRequest(BaseModel):\n user_input: str\n\n@app.post(\"/generate-knowledge\")\nasync def generate_knowledge(request: GenerateKnowledgeRequest):\n \"\"\"Generate agent knowledge from user input and store it in the vector database.\"\"\"\n try:\n # Process user input to generate knowledge\n knowledge = knowledge_processor.process_user_input(request.user_input)\n \n # Store the generated knowledge in vector database\n ids = vector_store.add_texts(\n texts=knowledge[\"text_chunks\"],\n metadata=knowledge[\"metadata\"]\n )\n \n return {\n \"message\": \"Successfully generated and stored agent knowledge\",\n \"structured_knowledge\": knowledge[\"structured_knowledge\"],","source_hash":"85bcb196f52273b2dcef31794d490e2aa848062da63103c1d8b0b80db9560ff6","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.api.main.GenerateKnowledgeRequest","uri":"program://agent-knowledge-generator/class/src.api.main.GenerateKnowledgeRequest#L45-L46","kind":"class","name":"GenerateKnowledgeRequest","path":"src/api/main.py","language":"python","start_line":45,"end_line":46,"context_start_line":25,"context_end_line":66,"code":" allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\n# Load configuration\nwith open(\"config.yaml\", 'r') as f:\n config = yaml.safe_load(f)\n\n# Initialize vector store and knowledge processor\nvector_store = VectorStore()\nknowledge_processor = KnowledgeProcessor(api_key=os.getenv('OPENAI_API_KEY'))\n\nclass QueryRequest(BaseModel):\n query: str\n k: int = Field(default=5, gt=0, description=\"Number of results to return\")\n\nclass AddTextsRequest(BaseModel):\n texts: List[str]\n metadata: Optional[List[Dict]] = None\n\nclass GenerateKnowledgeRequest(BaseModel):\n user_input: str\n\n@app.post(\"/generate-knowledge\")\nasync def generate_knowledge(request: GenerateKnowledgeRequest):\n \"\"\"Generate agent knowledge from user input and store it in the vector database.\"\"\"\n try:\n # Process user input to generate knowledge\n knowledge = knowledge_processor.process_user_input(request.user_input)\n \n # Store the generated knowledge in vector database\n ids = vector_store.add_texts(\n texts=knowledge[\"text_chunks\"],\n metadata=knowledge[\"metadata\"]\n )\n \n return {\n \"message\": \"Successfully generated and stored agent knowledge\",\n \"structured_knowledge\": knowledge[\"structured_knowledge\"],\n \"vector_ids\": ids\n }\n except Exception as e:","source_hash":"85bcb196f52273b2dcef31794d490e2aa848062da63103c1d8b0b80db9560ff6","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.api.main.generate_knowledge","uri":"program://agent-knowledge-generator/function/src.api.main.generate_knowledge#L49-L68","kind":"function","name":"generate_knowledge","path":"src/api/main.py","language":"python","start_line":49,"end_line":68,"context_start_line":29,"context_end_line":88,"code":"# Load configuration\nwith open(\"config.yaml\", 'r') as f:\n config = yaml.safe_load(f)\n\n# Initialize vector store and knowledge processor\nvector_store = VectorStore()\nknowledge_processor = KnowledgeProcessor(api_key=os.getenv('OPENAI_API_KEY'))\n\nclass QueryRequest(BaseModel):\n query: str\n k: int = Field(default=5, gt=0, description=\"Number of results to return\")\n\nclass AddTextsRequest(BaseModel):\n texts: List[str]\n metadata: Optional[List[Dict]] = None\n\nclass GenerateKnowledgeRequest(BaseModel):\n user_input: str\n\n@app.post(\"/generate-knowledge\")\nasync def generate_knowledge(request: GenerateKnowledgeRequest):\n \"\"\"Generate agent knowledge from user input and store it in the vector database.\"\"\"\n try:\n # Process user input to generate knowledge\n knowledge = knowledge_processor.process_user_input(request.user_input)\n \n # Store the generated knowledge in vector database\n ids = vector_store.add_texts(\n texts=knowledge[\"text_chunks\"],\n metadata=knowledge[\"metadata\"]\n )\n \n return {\n \"message\": \"Successfully generated and stored agent knowledge\",\n \"structured_knowledge\": knowledge[\"structured_knowledge\"],\n \"vector_ids\": ids\n }\n except Exception as e:\n logger.error(f\"Knowledge generation error: {e}\")\n raise HTTPException(status_code=500, detail=str(e))\n\n@app.post(\"/search\")\nasync def search(request: QueryRequest):\n try:\n results = vector_store.search(request.query, k=request.k)\n return {\"results\": results}\n except Exception as e:\n logger.error(f\"Search error: {e}\")\n raise HTTPException(status_code=500, detail=str(e))\n\n@app.post(\"/add-texts\")\nasync def add_texts(request: AddTextsRequest):\n try:\n ids = vector_store.add_texts(request.texts, request.metadata)\n return {\"ids\": ids}\n except Exception as e:\n logger.error(f\"Add texts error: {e}\")\n raise HTTPException(status_code=500, detail=str(e))\n\n@app.get(\"/health\")","source_hash":"85bcb196f52273b2dcef31794d490e2aa848062da63103c1d8b0b80db9560ff6","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.api.main.search","uri":"program://agent-knowledge-generator/function/src.api.main.search#L71-L77","kind":"function","name":"search","path":"src/api/main.py","language":"python","start_line":71,"end_line":77,"context_start_line":51,"context_end_line":97,"code":" try:\n # Process user input to generate knowledge\n knowledge = knowledge_processor.process_user_input(request.user_input)\n \n # Store the generated knowledge in vector database\n ids = vector_store.add_texts(\n texts=knowledge[\"text_chunks\"],\n metadata=knowledge[\"metadata\"]\n )\n \n return {\n \"message\": \"Successfully generated and stored agent knowledge\",\n \"structured_knowledge\": knowledge[\"structured_knowledge\"],\n \"vector_ids\": ids\n }\n except Exception as e:\n logger.error(f\"Knowledge generation error: {e}\")\n raise HTTPException(status_code=500, detail=str(e))\n\n@app.post(\"/search\")\nasync def search(request: QueryRequest):\n try:\n results = vector_store.search(request.query, k=request.k)\n return {\"results\": results}\n except Exception as e:\n logger.error(f\"Search error: {e}\")\n raise HTTPException(status_code=500, detail=str(e))\n\n@app.post(\"/add-texts\")\nasync def add_texts(request: AddTextsRequest):\n try:\n ids = vector_store.add_texts(request.texts, request.metadata)\n return {\"ids\": ids}\n except Exception as e:\n logger.error(f\"Add texts error: {e}\")\n raise HTTPException(status_code=500, detail=str(e))\n\n@app.get(\"/health\")\nasync def health_check():\n return {\"status\": \"healthy\"}\n\nif __name__ == \"__main__\":\n import uvicorn\n uvicorn.run(\n \"main:app\",\n host=config['api']['host'],\n port=config['api']['port'],","source_hash":"85bcb196f52273b2dcef31794d490e2aa848062da63103c1d8b0b80db9560ff6","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.api.main.add_texts","uri":"program://agent-knowledge-generator/function/src.api.main.add_texts#L80-L86","kind":"function","name":"add_texts","path":"src/api/main.py","language":"python","start_line":80,"end_line":86,"context_start_line":60,"context_end_line":99,"code":" \n return {\n \"message\": \"Successfully generated and stored agent knowledge\",\n \"structured_knowledge\": knowledge[\"structured_knowledge\"],\n \"vector_ids\": ids\n }\n except Exception as e:\n logger.error(f\"Knowledge generation error: {e}\")\n raise HTTPException(status_code=500, detail=str(e))\n\n@app.post(\"/search\")\nasync def search(request: QueryRequest):\n try:\n results = vector_store.search(request.query, k=request.k)\n return {\"results\": results}\n except Exception as e:\n logger.error(f\"Search error: {e}\")\n raise HTTPException(status_code=500, detail=str(e))\n\n@app.post(\"/add-texts\")\nasync def add_texts(request: AddTextsRequest):\n try:\n ids = vector_store.add_texts(request.texts, request.metadata)\n return {\"ids\": ids}\n except Exception as e:\n logger.error(f\"Add texts error: {e}\")\n raise HTTPException(status_code=500, detail=str(e))\n\n@app.get(\"/health\")\nasync def health_check():\n return {\"status\": \"healthy\"}\n\nif __name__ == \"__main__\":\n import uvicorn\n uvicorn.run(\n \"main:app\",\n host=config['api']['host'],\n port=config['api']['port'],\n reload=True\n ) ","source_hash":"85bcb196f52273b2dcef31794d490e2aa848062da63103c1d8b0b80db9560ff6","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.api.main.health_check","uri":"program://agent-knowledge-generator/function/src.api.main.health_check#L89-L90","kind":"function","name":"health_check","path":"src/api/main.py","language":"python","start_line":89,"end_line":90,"context_start_line":69,"context_end_line":99,"code":"\n@app.post(\"/search\")\nasync def search(request: QueryRequest):\n try:\n results = vector_store.search(request.query, k=request.k)\n return {\"results\": results}\n except Exception as e:\n logger.error(f\"Search error: {e}\")\n raise HTTPException(status_code=500, detail=str(e))\n\n@app.post(\"/add-texts\")\nasync def add_texts(request: AddTextsRequest):\n try:\n ids = vector_store.add_texts(request.texts, request.metadata)\n return {\"ids\": ids}\n except Exception as e:\n logger.error(f\"Add texts error: {e}\")\n raise HTTPException(status_code=500, detail=str(e))\n\n@app.get(\"/health\")\nasync def health_check():\n return {\"status\": \"healthy\"}\n\nif __name__ == \"__main__\":\n import uvicorn\n uvicorn.run(\n \"main:app\",\n host=config['api']['host'],\n port=config['api']['port'],\n reload=True\n ) ","source_hash":"85bcb196f52273b2dcef31794d490e2aa848062da63103c1d8b0b80db9560ff6","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.chatgpt.openai","uri":"program://agent-knowledge-generator/module/src.chatgpt.openai#L1-L15","kind":"module","name":"src.chatgpt.openai","path":"src/chatgpt/openai.py","language":"python","start_line":1,"end_line":15,"context_start_line":1,"context_end_line":15,"code":"from openai import OpenAI\nclient = OpenAI()\n\ncompletion = client.chat.completions.create(\n model=\"gpt-4o\",\n messages=[\n {\"role\": \"developer\", \"content\": \"You are a helpful assistant.\"},\n {\n \"role\": \"user\",\n \"content\": \"Write a haiku about recursion in programming.\"\n }\n ]\n)\n\nprint(completion.choices[0].message)","source_hash":"7cdd8a9c09ce3e6b16df72f4ec45c8a13f807aa1ad3f1be64118860a161f016a","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.chatgpt.knowledge_processor","uri":"program://agent-knowledge-generator/module/src.chatgpt.knowledge_processor#L1-L104","kind":"module","name":"src.chatgpt.knowledge_processor","path":"src/chatgpt/knowledge_processor.py","language":"python","start_line":1,"end_line":104,"context_start_line":1,"context_end_line":104,"code":"from openai import OpenAI\nfrom typing import Dict, List, Optional\nimport json\nfrom loguru import logger\nimport os\n\nclass KnowledgeProcessor:\n def __init__(self, api_key: Optional[str] = None):\n \"\"\"Initialize the knowledge processor with OpenAI client.\"\"\"\n # Try to get API key from environment if not provided\n self.api_key = api_key or os.getenv('OPENAI_API_KEY')\n if not self.api_key:\n logger.warning(\"No OpenAI API key provided. Using mock responses for testing.\")\n self.client = OpenAI(api_key=self.api_key)\n \n def process_user_input(self, user_input: str) -> Dict:\n \"\"\"Process user input to generate agent knowledge and tools.\"\"\"\n try:\n # Generate structured knowledge from user input\n completion = self.client.chat.completions.create(\n model=\"gpt-4-1106-preview\",\n messages=[\n {\"role\": \"system\", \"content\": \"\"\"You are an AI assistant that helps generate structured knowledge and tools for an AI agent.\n Given user input about what knowledge/capabilities an agent should have, generate:\n 1. Core knowledge areas\n 2. Required tools and functions\n 3. Example queries/tasks the agent should handle\n \n Your response must be a valid JSON object with the following structure:\n {\n \"core_knowledge\": [{\"title\": \"string\", \"description\": \"string\"}],\n \"tools\": [{\"name\": \"string\", \"description\": \"string\"}],\n \"examples\": [{\"query\": \"string\", \"expected_response\": \"string\"}]\n }\"\"\"},\n {\"role\": \"user\", \"content\": user_input}\n ],\n response_format={\"type\": \"json_object\"}\n )\n \n # Parse the structured knowledge\n knowledge_base = json.loads(completion.choices[0].message.content)\n \n # Generate embeddings-ready text chunks\n text_chunks = self._generate_text_chunks(knowledge_base)\n \n return {\n \"structured_knowledge\": knowledge_base,\n \"text_chunks\": text_chunks,\n \"metadata\": self._generate_metadata(knowledge_base)\n }\n \n except Exception as e:\n logger.error(f\"Error processing user input: {e}\")\n raise\n \n def _generate_text_chunks(self, knowledge_base: Dict) -> List[str]:\n \"\"\"Convert structured knowledge into text chunks for embedding.\"\"\"\n chunks = []\n \n # Process core knowledge areas\n for area in knowledge_base.get(\"core_knowledge\", []):\n chunks.append(f\"Core Knowledge - {area['title']}: {area['description']}\")\n \n # Process tools and functions\n for tool in knowledge_base.get(\"tools\", []):\n chunks.append(f\"Tool - {tool['name']}: {tool['description']}\")\n if 'usage_example' in tool:\n chunks.append(f\"Tool Usage: {tool['usage_example']}\")\n \n # Process example queries/tasks\n for example in knowledge_base.get(\"examples\", []):\n chunks.append(f\"Example Task: {example['query']} -> {example['expected_response']}\")\n \n return chunks\n \n def _generate_metadata(self, knowledge_base: Dict) -> List[Dict]:\n \"\"\"Generate metadata for each text chunk.\"\"\"\n metadata = []\n \n # Add metadata for each chunk corresponding to _generate_text_chunks\n for area in knowledge_base.get(\"core_knowledge\", []):\n metadata.append({\n \"type\": \"core_knowledge\",\n \"title\": area[\"title\"]\n })\n \n for tool in knowledge_base.get(\"tools\", []):\n metadata.append({\n \"type\": \"tool\",\n \"name\": tool[\"name\"]\n })\n if 'usage_example' in tool:\n metadata.append({\n \"type\": \"tool_usage\",\n \"name\": tool[\"name\"]\n })\n \n for example in knowledge_base.get(\"examples\", []):\n metadata.append({\n \"type\": \"example\",\n \"query\": example[\"query\"]\n })\n \n return metadata ","source_hash":"4bc66a7420553354601ef96c0ca1ccb13bf26e799ac59a8437a4211bd93fd03b","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.chatgpt.knowledge_processor.KnowledgeProcessor","uri":"program://agent-knowledge-generator/class/src.chatgpt.knowledge_processor.KnowledgeProcessor#L7-L104","kind":"class","name":"KnowledgeProcessor","path":"src/chatgpt/knowledge_processor.py","language":"python","start_line":7,"end_line":104,"context_start_line":1,"context_end_line":104,"code":"from openai import OpenAI\nfrom typing import Dict, List, Optional\nimport json\nfrom loguru import logger\nimport os\n\nclass KnowledgeProcessor:\n def __init__(self, api_key: Optional[str] = None):\n \"\"\"Initialize the knowledge processor with OpenAI client.\"\"\"\n # Try to get API key from environment if not provided\n self.api_key = api_key or os.getenv('OPENAI_API_KEY')\n if not self.api_key:\n logger.warning(\"No OpenAI API key provided. Using mock responses for testing.\")\n self.client = OpenAI(api_key=self.api_key)\n \n def process_user_input(self, user_input: str) -> Dict:\n \"\"\"Process user input to generate agent knowledge and tools.\"\"\"\n try:\n # Generate structured knowledge from user input\n completion = self.client.chat.completions.create(\n model=\"gpt-4-1106-preview\",\n messages=[\n {\"role\": \"system\", \"content\": \"\"\"You are an AI assistant that helps generate structured knowledge and tools for an AI agent.\n Given user input about what knowledge/capabilities an agent should have, generate:\n 1. Core knowledge areas\n 2. Required tools and functions\n 3. Example queries/tasks the agent should handle\n \n Your response must be a valid JSON object with the following structure:\n {\n \"core_knowledge\": [{\"title\": \"string\", \"description\": \"string\"}],\n \"tools\": [{\"name\": \"string\", \"description\": \"string\"}],\n \"examples\": [{\"query\": \"string\", \"expected_response\": \"string\"}]\n }\"\"\"},\n {\"role\": \"user\", \"content\": user_input}\n ],\n response_format={\"type\": \"json_object\"}\n )\n \n # Parse the structured knowledge\n knowledge_base = json.loads(completion.choices[0].message.content)\n \n # Generate embeddings-ready text chunks\n text_chunks = self._generate_text_chunks(knowledge_base)\n \n return {\n \"structured_knowledge\": knowledge_base,\n \"text_chunks\": text_chunks,\n \"metadata\": self._generate_metadata(knowledge_base)\n }\n \n except Exception as e:\n logger.error(f\"Error processing user input: {e}\")\n raise\n \n def _generate_text_chunks(self, knowledge_base: Dict) -> List[str]:\n \"\"\"Convert structured knowledge into text chunks for embedding.\"\"\"\n chunks = []\n \n # Process core knowledge areas\n for area in knowledge_base.get(\"core_knowledge\", []):\n chunks.append(f\"Core Knowledge - {area['title']}: {area['description']}\")\n \n # Process tools and functions\n for tool in knowledge_base.get(\"tools\", []):\n chunks.append(f\"Tool - {tool['name']}: {tool['description']}\")\n if 'usage_example' in tool:\n chunks.append(f\"Tool Usage: {tool['usage_example']}\")\n \n # Process example queries/tasks\n for example in knowledge_base.get(\"examples\", []):\n chunks.append(f\"Example Task: {example['query']} -> {example['expected_response']}\")\n \n return chunks\n \n def _generate_metadata(self, knowledge_base: Dict) -> List[Dict]:\n \"\"\"Generate metadata for each text chunk.\"\"\"\n metadata = []\n \n # Add metadata for each chunk corresponding to _generate_text_chunks\n for area in knowledge_base.get(\"core_knowledge\", []):\n metadata.append({\n \"type\": \"core_knowledge\",\n \"title\": area[\"title\"]\n })\n \n for tool in knowledge_base.get(\"tools\", []):\n metadata.append({\n \"type\": \"tool\",\n \"name\": tool[\"name\"]\n })\n if 'usage_example' in tool:\n metadata.append({\n \"type\": \"tool_usage\",\n \"name\": tool[\"name\"]\n })\n \n for example in knowledge_base.get(\"examples\", []):\n metadata.append({\n \"type\": \"example\",\n \"query\": example[\"query\"]\n })\n \n return metadata ","source_hash":"4bc66a7420553354601ef96c0ca1ccb13bf26e799ac59a8437a4211bd93fd03b","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.chatgpt.knowledge_processor.__init__","uri":"program://agent-knowledge-generator/function/src.chatgpt.knowledge_processor.__init__#L8-L14","kind":"function","name":"__init__","path":"src/chatgpt/knowledge_processor.py","language":"python","start_line":8,"end_line":14,"context_start_line":1,"context_end_line":34,"code":"from openai import OpenAI\nfrom typing import Dict, List, Optional\nimport json\nfrom loguru import logger\nimport os\n\nclass KnowledgeProcessor:\n def __init__(self, api_key: Optional[str] = None):\n \"\"\"Initialize the knowledge processor with OpenAI client.\"\"\"\n # Try to get API key from environment if not provided\n self.api_key = api_key or os.getenv('OPENAI_API_KEY')\n if not self.api_key:\n logger.warning(\"No OpenAI API key provided. Using mock responses for testing.\")\n self.client = OpenAI(api_key=self.api_key)\n \n def process_user_input(self, user_input: str) -> Dict:\n \"\"\"Process user input to generate agent knowledge and tools.\"\"\"\n try:\n # Generate structured knowledge from user input\n completion = self.client.chat.completions.create(\n model=\"gpt-4-1106-preview\",\n messages=[\n {\"role\": \"system\", \"content\": \"\"\"You are an AI assistant that helps generate structured knowledge and tools for an AI agent.\n Given user input about what knowledge/capabilities an agent should have, generate:\n 1. Core knowledge areas\n 2. Required tools and functions\n 3. Example queries/tasks the agent should handle\n \n Your response must be a valid JSON object with the following structure:\n {\n \"core_knowledge\": [{\"title\": \"string\", \"description\": \"string\"}],\n \"tools\": [{\"name\": \"string\", \"description\": \"string\"}],\n \"examples\": [{\"query\": \"string\", \"expected_response\": \"string\"}]\n }\"\"\"},","source_hash":"4bc66a7420553354601ef96c0ca1ccb13bf26e799ac59a8437a4211bd93fd03b","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.chatgpt.knowledge_processor.process_user_input","uri":"program://agent-knowledge-generator/function/src.chatgpt.knowledge_processor.process_user_input#L16-L54","kind":"function","name":"process_user_input","path":"src/chatgpt/knowledge_processor.py","language":"python","start_line":16,"end_line":54,"context_start_line":1,"context_end_line":74,"code":"from openai import OpenAI\nfrom typing import Dict, List, Optional\nimport json\nfrom loguru import logger\nimport os\n\nclass KnowledgeProcessor:\n def __init__(self, api_key: Optional[str] = None):\n \"\"\"Initialize the knowledge processor with OpenAI client.\"\"\"\n # Try to get API key from environment if not provided\n self.api_key = api_key or os.getenv('OPENAI_API_KEY')\n if not self.api_key:\n logger.warning(\"No OpenAI API key provided. Using mock responses for testing.\")\n self.client = OpenAI(api_key=self.api_key)\n \n def process_user_input(self, user_input: str) -> Dict:\n \"\"\"Process user input to generate agent knowledge and tools.\"\"\"\n try:\n # Generate structured knowledge from user input\n completion = self.client.chat.completions.create(\n model=\"gpt-4-1106-preview\",\n messages=[\n {\"role\": \"system\", \"content\": \"\"\"You are an AI assistant that helps generate structured knowledge and tools for an AI agent.\n Given user input about what knowledge/capabilities an agent should have, generate:\n 1. Core knowledge areas\n 2. Required tools and functions\n 3. Example queries/tasks the agent should handle\n \n Your response must be a valid JSON object with the following structure:\n {\n \"core_knowledge\": [{\"title\": \"string\", \"description\": \"string\"}],\n \"tools\": [{\"name\": \"string\", \"description\": \"string\"}],\n \"examples\": [{\"query\": \"string\", \"expected_response\": \"string\"}]\n }\"\"\"},\n {\"role\": \"user\", \"content\": user_input}\n ],\n response_format={\"type\": \"json_object\"}\n )\n \n # Parse the structured knowledge\n knowledge_base = json.loads(completion.choices[0].message.content)\n \n # Generate embeddings-ready text chunks\n text_chunks = self._generate_text_chunks(knowledge_base)\n \n return {\n \"structured_knowledge\": knowledge_base,\n \"text_chunks\": text_chunks,\n \"metadata\": self._generate_metadata(knowledge_base)\n }\n \n except Exception as e:\n logger.error(f\"Error processing user input: {e}\")\n raise\n \n def _generate_text_chunks(self, knowledge_base: Dict) -> List[str]:\n \"\"\"Convert structured knowledge into text chunks for embedding.\"\"\"\n chunks = []\n \n # Process core knowledge areas\n for area in knowledge_base.get(\"core_knowledge\", []):\n chunks.append(f\"Core Knowledge - {area['title']}: {area['description']}\")\n \n # Process tools and functions\n for tool in knowledge_base.get(\"tools\", []):\n chunks.append(f\"Tool - {tool['name']}: {tool['description']}\")\n if 'usage_example' in tool:\n chunks.append(f\"Tool Usage: {tool['usage_example']}\")\n \n # Process example queries/tasks\n for example in knowledge_base.get(\"examples\", []):\n chunks.append(f\"Example Task: {example['query']} -> {example['expected_response']}\")\n \n return chunks","source_hash":"4bc66a7420553354601ef96c0ca1ccb13bf26e799ac59a8437a4211bd93fd03b","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.chatgpt.knowledge_processor._generate_text_chunks","uri":"program://agent-knowledge-generator/function/src.chatgpt.knowledge_processor._generate_text_chunks#L56-L74","kind":"function","name":"_generate_text_chunks","path":"src/chatgpt/knowledge_processor.py","language":"python","start_line":56,"end_line":74,"context_start_line":36,"context_end_line":94,"code":" ],\n response_format={\"type\": \"json_object\"}\n )\n \n # Parse the structured knowledge\n knowledge_base = json.loads(completion.choices[0].message.content)\n \n # Generate embeddings-ready text chunks\n text_chunks = self._generate_text_chunks(knowledge_base)\n \n return {\n \"structured_knowledge\": knowledge_base,\n \"text_chunks\": text_chunks,\n \"metadata\": self._generate_metadata(knowledge_base)\n }\n \n except Exception as e:\n logger.error(f\"Error processing user input: {e}\")\n raise\n \n def _generate_text_chunks(self, knowledge_base: Dict) -> List[str]:\n \"\"\"Convert structured knowledge into text chunks for embedding.\"\"\"\n chunks = []\n \n # Process core knowledge areas\n for area in knowledge_base.get(\"core_knowledge\", []):\n chunks.append(f\"Core Knowledge - {area['title']}: {area['description']}\")\n \n # Process tools and functions\n for tool in knowledge_base.get(\"tools\", []):\n chunks.append(f\"Tool - {tool['name']}: {tool['description']}\")\n if 'usage_example' in tool:\n chunks.append(f\"Tool Usage: {tool['usage_example']}\")\n \n # Process example queries/tasks\n for example in knowledge_base.get(\"examples\", []):\n chunks.append(f\"Example Task: {example['query']} -> {example['expected_response']}\")\n \n return chunks\n \n def _generate_metadata(self, knowledge_base: Dict) -> List[Dict]:\n \"\"\"Generate metadata for each text chunk.\"\"\"\n metadata = []\n \n # Add metadata for each chunk corresponding to _generate_text_chunks\n for area in knowledge_base.get(\"core_knowledge\", []):\n metadata.append({\n \"type\": \"core_knowledge\",\n \"title\": area[\"title\"]\n })\n \n for tool in knowledge_base.get(\"tools\", []):\n metadata.append({\n \"type\": \"tool\",\n \"name\": tool[\"name\"]\n })\n if 'usage_example' in tool:\n metadata.append({\n \"type\": \"tool_usage\",","source_hash":"4bc66a7420553354601ef96c0ca1ccb13bf26e799ac59a8437a4211bd93fd03b","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"py:src.chatgpt.knowledge_processor._generate_metadata","uri":"program://agent-knowledge-generator/function/src.chatgpt.knowledge_processor._generate_metadata#L76-L104","kind":"function","name":"_generate_metadata","path":"src/chatgpt/knowledge_processor.py","language":"python","start_line":76,"end_line":104,"context_start_line":56,"context_end_line":104,"code":" def _generate_text_chunks(self, knowledge_base: Dict) -> List[str]:\n \"\"\"Convert structured knowledge into text chunks for embedding.\"\"\"\n chunks = []\n \n # Process core knowledge areas\n for area in knowledge_base.get(\"core_knowledge\", []):\n chunks.append(f\"Core Knowledge - {area['title']}: {area['description']}\")\n \n # Process tools and functions\n for tool in knowledge_base.get(\"tools\", []):\n chunks.append(f\"Tool - {tool['name']}: {tool['description']}\")\n if 'usage_example' in tool:\n chunks.append(f\"Tool Usage: {tool['usage_example']}\")\n \n # Process example queries/tasks\n for example in knowledge_base.get(\"examples\", []):\n chunks.append(f\"Example Task: {example['query']} -> {example['expected_response']}\")\n \n return chunks\n \n def _generate_metadata(self, knowledge_base: Dict) -> List[Dict]:\n \"\"\"Generate metadata for each text chunk.\"\"\"\n metadata = []\n \n # Add metadata for each chunk corresponding to _generate_text_chunks\n for area in knowledge_base.get(\"core_knowledge\", []):\n metadata.append({\n \"type\": \"core_knowledge\",\n \"title\": area[\"title\"]\n })\n \n for tool in knowledge_base.get(\"tools\", []):\n metadata.append({\n \"type\": \"tool\",\n \"name\": tool[\"name\"]\n })\n if 'usage_example' in tool:\n metadata.append({\n \"type\": \"tool_usage\",\n \"name\": tool[\"name\"]\n })\n \n for example in knowledge_base.get(\"examples\", []):\n metadata.append({\n \"type\": \"example\",\n \"query\": example[\"query\"]\n })\n \n return metadata ","source_hash":"4bc66a7420553354601ef96c0ca1ccb13bf26e799ac59a8437a4211bd93fd03b","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"file:tests/conftest.py","uri":"program://agent-knowledge-generator/file/tests/conftest.py","kind":"file","name":"tests/conftest.py","path":"tests/conftest.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import pytest\nimport os\nimport sys\nfrom unittest.mock import Mock, patch\nimport numpy as np\n\n# Add the src directory to the Python path\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n\n# Create mock for sentence transformers before any tests run\n@pytest.fixture(autouse=True)\ndef mock_dependencies():\n \"\"\"Mock external dependencies for all tests.\"\"\"\n mock_sentence_transformer = Mock()\n mock_sentence_transformer.encode.return_value = np.random.rand(1, 384).astype('float32')\n \n with patch.dict('sys.modules', {\n 'sentence_transformers': Mock(),\n 'sentence_transformers.SentenceTransformer': Mock(return_value=mock_sentence_transformer),\n 'tensorflow': Mock(),\n 'torch': Mock()","source_hash":"6e8fd33cb63298d33534420107fd18ed9a530fa4a53a2c24ad4eee7aec0e8b85","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"file:tests/test_vector_store.py","uri":"program://agent-knowledge-generator/file/tests/test_vector_store.py","kind":"file","name":"tests/test_vector_store.py","path":"tests/test_vector_store.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import pytest\nimport numpy as np\nimport os\nimport sys\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nfrom src.database.vector_store import VectorStore\n\n@pytest.fixture\ndef vector_store():\n \"\"\"Create a real VectorStore instance.\"\"\"\n return VectorStore()\n\ndef test_preprocess_text(vector_store):\n \"\"\"Test text preprocessing.\"\"\"\n text = \"Hello, World! This is a TEST.\"\n words = vector_store._preprocess_text(text)\n assert words == ['hello', 'world', 'this', 'is', 'a', 'test']\n\ndef test_basic_embedding_flow(vector_store):\n \"\"\"Test the basic flow of adding and searching texts.\"\"\"","source_hash":"7d223ddadf8bceadc5029f525317fba34b4a3854107f1b139df997df1ca08677","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"file:tests/test_system_logger.py","uri":"program://agent-knowledge-generator/file/tests/test_system_logger.py","kind":"file","name":"tests/test_system_logger.py","path":"tests/test_system_logger.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import pytest\nimport json\nimport os\nfrom datetime import datetime\nimport sys\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nfrom src.utils.logger import SystemLogger\n\n@pytest.fixture\ndef temp_log_files(tmp_path):\n actions_log = tmp_path / \"actions.log\"\n thoughts_log = tmp_path / \"thoughts.log\"\n return str(actions_log), str(thoughts_log)\n\n@pytest.fixture\ndef system_logger(temp_log_files):\n actions_log, thoughts_log = temp_log_files\n return SystemLogger(actions_log_path=actions_log, thoughts_log_path=thoughts_log)\n\ndef test_log_file_creation(temp_log_files):","source_hash":"b8b96652a6663b42e6a900902fca184c018c37c0404d68087d174c27f755a1c2","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"file:tests/test_api.py","uri":"program://agent-knowledge-generator/file/tests/test_api.py","kind":"file","name":"tests/test_api.py","path":"tests/test_api.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import pytest\nfrom fastapi.testclient import TestClient\nimport os\nimport sys\nfrom dotenv import load_dotenv\n\n# Load environment variables before importing app\nload_dotenv()\n\n# Ensure we have an API key for tests\nif not os.getenv('OPENAI_API_KEY'):\n pytest.skip(\"Skipping tests that require OpenAI API key\", allow_module_level=True)\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nfrom src.api.main import app\n\n@pytest.fixture\ndef client():\n \"\"\"Create a test client.\"\"\"\n return TestClient(app)\n","source_hash":"bb6ddb3e844398070bbdb391e83b33fc18d86b7f1e2cfac09a5457371bef3f36","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"file:tests/test_knowledge_processor.py","uri":"program://agent-knowledge-generator/file/tests/test_knowledge_processor.py","kind":"file","name":"tests/test_knowledge_processor.py","path":"tests/test_knowledge_processor.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import pytest\nfrom unittest.mock import patch, MagicMock\nimport json\nimport os\nimport sys\nfrom dotenv import load_dotenv\n\n# Load environment variables from .env\nload_dotenv()\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nfrom src.chatgpt.knowledge_processor import KnowledgeProcessor\n\n@pytest.fixture\ndef mock_openai():\n \"\"\"Create a mock OpenAI client.\"\"\"\n mock_response = {\n \"choices\": [{\n \"message\": {\n \"content\": json.dumps({\n \"core_knowledge\": [","source_hash":"2176de273db97e275e071785b7aea5fa72bbc6aac6f3131d3a293422a81f46c0","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"file:src/database/vector_store.py","uri":"program://agent-knowledge-generator/file/src/database/vector_store.py","kind":"file","name":"src/database/vector_store.py","path":"src/database/vector_store.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"from typing import List, Dict, Any, Optional\nimport faiss\nimport numpy as np\nfrom loguru import logger\nimport yaml\nimport os\nimport re\nfrom collections import Counter\n\nclass VectorStore:\n def __init__(self, config_path: str = \"config.yaml\"):\n with open(config_path, 'r') as f:\n self.config = yaml.safe_load(f)\n \n self.index = None\n self.metadata = {}\n self.dimension = 100 # Fixed dimension for our simple embeddings\n self.vocabulary = {} # Word to index mapping\n self.next_word_index = 0\n \n def _preprocess_text(self, text: str) -> List[str]:","source_hash":"dee13db66543a35032a79d476fd2799e5abf482b7e58647269af148f0cf4c264","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"file:src/utils/data_processor.py","uri":"program://agent-knowledge-generator/file/src/utils/data_processor.py","kind":"file","name":"src/utils/data_processor.py","path":"src/utils/data_processor.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"from typing import List, Dict, Any, Tuple\nimport pandas as pd\nimport json\nfrom loguru import logger\n\nclass DataProcessor:\n @staticmethod\n def process_file(file_path: str, file_format: str) -> Tuple[List[str], List[Dict]]:\n \"\"\"Process input file and return texts and metadata.\"\"\"\n try:\n if file_format == 'csv':\n return DataProcessor._process_csv(file_path)\n elif file_format == 'json':\n return DataProcessor._process_json(file_path)\n elif file_format == 'txt':\n return DataProcessor._process_txt(file_path)\n else:\n raise ValueError(f\"Unsupported file format: {file_format}\")\n except Exception as e:\n logger.error(f\"Error processing file: {e}\")\n raise","source_hash":"fdcf1488a59ab6c2de0381162fcb49b4fd1598c70f2bc161084ca77755f17953","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"file:src/utils/logger.py","uri":"program://agent-knowledge-generator/file/src/utils/logger.py","kind":"file","name":"src/utils/logger.py","path":"src/utils/logger.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import json\nfrom datetime import datetime\nfrom typing import Any, Dict, Optional\nimport os\nfrom pathlib import Path\n\nclass SystemLogger:\n def __init__(self, actions_log_path: str = \"actions.log\", thoughts_log_path: str = \"thoughts.log\"):\n \"\"\"Initialize the system logger.\"\"\"\n self.actions_log_path = actions_log_path\n self.thoughts_log_path = thoughts_log_path\n self._ensure_log_files_exist()\n \n def _ensure_log_files_exist(self):\n \"\"\"Ensure log files exist and create them if they don't.\"\"\"\n for path in [self.actions_log_path, self.thoughts_log_path]:\n Path(path).touch(exist_ok=True)\n \n def _format_log_entry(self, entry_type: str, message: str, metadata: Optional[Dict[str, Any]] = None) -> str:\n \"\"\"Format a log entry as JSON.\"\"\"\n log_entry = {","source_hash":"f7967623f0de2be44890fd63622d6700c1ade5cf9dab2905cfd67fcc0df40db8","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"file:src/api/main.py","uri":"program://agent-knowledge-generator/file/src/api/main.py","kind":"file","name":"src/api/main.py","path":"src/api/main.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"from fastapi import FastAPI, UploadFile, HTTPException\nfrom fastapi.middleware.cors import CORSMiddleware\nfrom pydantic import BaseModel, Field\nfrom typing import List, Optional, Dict\nimport yaml\nfrom loguru import logger\nimport sys\nimport os\nfrom dotenv import load_dotenv\n\n# Load environment variables\nload_dotenv()\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nfrom database.vector_store import VectorStore\nfrom chatgpt.knowledge_processor import KnowledgeProcessor\n\napp = FastAPI(title=\"RAG Vector Database API\")\n\n# CORS middleware\napp.add_middleware(","source_hash":"85bcb196f52273b2dcef31794d490e2aa848062da63103c1d8b0b80db9560ff6","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"file:src/chatgpt/openai.py","uri":"program://agent-knowledge-generator/file/src/chatgpt/openai.py","kind":"file","name":"src/chatgpt/openai.py","path":"src/chatgpt/openai.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":15,"code":"from openai import OpenAI\nclient = OpenAI()\n\ncompletion = client.chat.completions.create(\n model=\"gpt-4o\",\n messages=[\n {\"role\": \"developer\", \"content\": \"You are a helpful assistant.\"},\n {\n \"role\": \"user\",\n \"content\": \"Write a haiku about recursion in programming.\"\n }\n ]\n)\n\nprint(completion.choices[0].message)","source_hash":"7cdd8a9c09ce3e6b16df72f4ec45c8a13f807aa1ad3f1be64118860a161f016a","truncated":false}
{"repo_id":"agent-knowledge-generator","entity_id":"file:src/chatgpt/knowledge_processor.py","uri":"program://agent-knowledge-generator/file/src/chatgpt/knowledge_processor.py","kind":"file","name":"src/chatgpt/knowledge_processor.py","path":"src/chatgpt/knowledge_processor.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"from openai import OpenAI\nfrom typing import Dict, List, Optional\nimport json\nfrom loguru import logger\nimport os\n\nclass KnowledgeProcessor:\n def __init__(self, api_key: Optional[str] = None):\n \"\"\"Initialize the knowledge processor with OpenAI client.\"\"\"\n # Try to get API key from environment if not provided\n self.api_key = api_key or os.getenv('OPENAI_API_KEY')\n if not self.api_key:\n logger.warning(\"No OpenAI API key provided. Using mock responses for testing.\")\n self.client = OpenAI(api_key=self.api_key)\n \n def process_user_input(self, user_input: str) -> Dict:\n \"\"\"Process user input to generate agent knowledge and tools.\"\"\"\n try:\n # Generate structured knowledge from user input\n completion = self.client.chat.completions.create(\n model=\"gpt-4-1106-preview\",","source_hash":"4bc66a7420553354601ef96c0ca1ccb13bf26e799ac59a8437a4211bd93fd03b","truncated":false}