experia 0.2.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
experia/__init__.py ADDED
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
@@ -0,0 +1,32 @@
1
+ from typing import List
2
+
3
+ from experia.memory.models import Memory
4
+
5
+
6
+ class ContextBuilder:
7
+ """
8
+ Transforms raw memories into structured, usable intelligence for the agent.
9
+ """
10
+
11
+ def format_for_prompt(self, memories: List[Memory]) -> str:
12
+ """
13
+ Takes a list of memories and formats them into a text string
14
+ that can be injected into an LLM system prompt.
15
+ """
16
+ if not memories:
17
+ return ""
18
+
19
+ context_lines = ["--- User Context & Learned Experience ---"]
20
+
21
+ # Group by type for better readability by the LLM
22
+ grouped_memories = {}
23
+ for mem in memories:
24
+ grouped_memories.setdefault(mem.type.value, []).append(mem)
25
+
26
+ for mem_type, type_memories in grouped_memories.items():
27
+ context_lines.append(f"\n[{mem_type.upper()}]")
28
+ for mem in type_memories:
29
+ context_lines.append(f"- {mem.content}")
30
+
31
+ context_lines.append("\n---------------------------------------")
32
+ return "\n".join(context_lines)
File without changes
@@ -0,0 +1,22 @@
1
+ class ExperiaError(Exception):
2
+ """Base exception for all Experia errors."""
3
+
4
+ pass
5
+
6
+
7
+ class StorageError(ExperiaError):
8
+ """Raised when a storage operation fails."""
9
+
10
+ pass
11
+
12
+
13
+ class EvaluationError(ExperiaError):
14
+ """Raised when an experience evaluation fails."""
15
+
16
+ pass
17
+
18
+
19
+ class ConfigurationError(ExperiaError):
20
+ """Raised when Experia is misconfigured."""
21
+
22
+ pass
@@ -0,0 +1,32 @@
1
+ from typing import List, Optional, Protocol
2
+ from uuid import UUID
3
+
4
+ from experia.experience.models import ExperienceRecord, Lesson
5
+ from experia.memory.models import Memory, MemoryType
6
+
7
+
8
+ class MemoryStore(Protocol):
9
+ """Protocol for memory and experience storage backends."""
10
+
11
+ async def save_experience(self, experience: ExperienceRecord) -> None: ...
12
+
13
+ async def get_experience(
14
+ self, experience_id: UUID
15
+ ) -> Optional[ExperienceRecord]: ...
16
+
17
+ async def save_lesson(self, lesson: Lesson) -> None: ...
18
+
19
+ async def save_memory(self, memory: Memory) -> None: ...
20
+
21
+ async def search_memories(
22
+ self,
23
+ query: str = "",
24
+ memory_type: Optional[MemoryType] = None,
25
+ limit: int = 10,
26
+ ) -> List[Memory]: ...
27
+
28
+
29
+ class Evaluator(Protocol):
30
+ """Protocol for experience evaluators."""
31
+
32
+ async def evaluate(self, experience: ExperienceRecord) -> Optional[Lesson]: ...
@@ -0,0 +1,85 @@
1
+ from typing import Any, Dict, Optional
2
+
3
+ from experia.context.builder import ContextBuilder
4
+ from experia.core.exceptions import ConfigurationError
5
+ from experia.core.interfaces import Evaluator, MemoryStore
6
+ from experia.core.logging import logger
7
+ from experia.experience.models import ExperienceRecord
8
+ from experia.improvement.rules import RuleGenerator
9
+ from experia.memory.models import Memory, MemoryType
10
+
11
+
12
+ class Learner:
13
+ """
14
+ The main asynchronous entry point for the Experia AI Cognitive Layer.
15
+ Uses Dependency Injection to accept any MemoryStore and Evaluator implementations.
16
+ """
17
+
18
+ def __init__(
19
+ self,
20
+ store: MemoryStore,
21
+ evaluator: Evaluator,
22
+ rule_generator: Optional[RuleGenerator] = None,
23
+ ):
24
+ if not store or not evaluator:
25
+ raise ConfigurationError("Learner requires both a store and an evaluator.")
26
+
27
+ self.store = store
28
+ self.evaluator = evaluator
29
+ self.rule_generator = rule_generator
30
+ self.context_builder = ContextBuilder()
31
+ logger.info("Experia Learner initialized successfully.")
32
+
33
+ async def record(
34
+ self,
35
+ task: str,
36
+ action: str,
37
+ result: str,
38
+ context: Optional[Dict[str, Any]] = None,
39
+ ) -> ExperienceRecord:
40
+ """Records an agent's action and its result asynchronously."""
41
+ experience = ExperienceRecord(
42
+ task=task, action=action, result=result, context=context or {}
43
+ )
44
+ await self.store.save_experience(experience)
45
+ logger.debug(f"Recorded experience {experience.id} for task '{task}'")
46
+
47
+ await self._evaluate_and_remember(experience)
48
+ return experience
49
+
50
+ async def _evaluate_and_remember(self, experience: ExperienceRecord) -> None:
51
+ """Internal asynchronous method to evaluate an experience and store its lesson."""
52
+ lesson = await self.evaluator.evaluate(experience)
53
+ if lesson:
54
+ await self.store.save_lesson(lesson)
55
+
56
+ memory = Memory(
57
+ content=lesson.content,
58
+ type=MemoryType.LESSON,
59
+ confidence=lesson.confidence,
60
+ importance=0.7,
61
+ source=f"Experience:{experience.id}",
62
+ )
63
+ await self.store.save_memory(memory)
64
+ logger.info(
65
+ f"Learned and remembered lesson from experience {experience.id}"
66
+ )
67
+
68
+ # Optionally generate a global rule
69
+ if self.rule_generator:
70
+ await self.rule_generator.consolidate_lesson(lesson)
71
+
72
+ async def retrieve_context(self, query: str = "", limit: int = 5) -> str:
73
+ """Searches cognitive memory and builds a prompt string asynchronously."""
74
+ memories = await self.store.search_memories(query=query, limit=limit)
75
+ logger.debug(f"Retrieved {len(memories)} memories for context.")
76
+ return self.context_builder.format_for_prompt(memories)
77
+
78
+ async def remember(
79
+ self, content: str, memory_type: MemoryType = MemoryType.FACT
80
+ ) -> Memory:
81
+ """Manually add a piece of knowledge to the memory store asynchronously."""
82
+ memory = Memory(content=content, type=memory_type, importance=0.9)
83
+ await self.store.save_memory(memory)
84
+ logger.debug(f"Manually remembered explicit knowledge: {memory.id}")
85
+ return memory
@@ -0,0 +1,17 @@
1
+ import logging
2
+
3
+ # Configure the package-level logger
4
+ logger = logging.getLogger("experia")
5
+
6
+ # Prevent log propagation to the root logger by default to avoid duplicate logs
7
+ # if the user hasn't configured a handler.
8
+ logger.propagate = False
9
+
10
+ if not logger.handlers:
11
+ handler = logging.StreamHandler()
12
+ formatter = logging.Formatter(
13
+ "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
14
+ )
15
+ handler.setFormatter(formatter)
16
+ logger.addHandler(handler)
17
+ logger.setLevel(logging.INFO)
File without changes
File without changes
@@ -0,0 +1,38 @@
1
+ from typing import Optional
2
+
3
+ from experia.core.interfaces import Evaluator
4
+ from experia.core.logging import logger
5
+ from experia.experience.models import ExperienceRecord, Lesson
6
+
7
+
8
+ class SimpleHeuristicEvaluator(Evaluator):
9
+ """
10
+ An asynchronous heuristic-based evaluator for testing and basic usage.
11
+ Implements the Evaluator Protocol.
12
+ """
13
+
14
+ async def evaluate(self, experience: ExperienceRecord) -> Optional[Lesson]:
15
+ """Evaluates the experience asynchronously."""
16
+ lower_result = experience.result.lower()
17
+
18
+ if "fail" in lower_result or "error" in lower_result:
19
+ content = (
20
+ f"The action '{experience.action}' failed during "
21
+ f"'{experience.task}'. Ensure prerequisites are met before retrying."
22
+ )
23
+ confidence = 0.6
24
+ logger.info(f"Evaluator detected failure for experience {experience.id}")
25
+ elif "success" in lower_result:
26
+ content = (
27
+ f"The action '{experience.action}' was successful for "
28
+ f"'{experience.task}'. This strategy works."
29
+ )
30
+ confidence = 0.8
31
+ logger.info(f"Evaluator detected success for experience {experience.id}")
32
+ else:
33
+ logger.debug(f"No actionable lesson found for experience {experience.id}")
34
+ return None
35
+
36
+ return Lesson(
37
+ experience_id=experience.id, content=content, confidence=confidence
38
+ )
File without changes
@@ -0,0 +1,86 @@
1
+ import json
2
+ from typing import Optional
3
+
4
+ from pydantic import BaseModel, Field
5
+
6
+ from experia.core.exceptions import EvaluationError
7
+ from experia.core.interfaces import Evaluator
8
+ from experia.core.logging import logger
9
+ from experia.experience.models import ExperienceRecord, Lesson
10
+
11
+ try:
12
+ import litellm
13
+ except ImportError:
14
+ litellm = None
15
+
16
+
17
+ class EvaluatorResponseSchema(BaseModel):
18
+ """Internal schema to force structured JSON output from the LLM."""
19
+
20
+ lesson: str = Field(description="The extracted lesson or behavioral rule.")
21
+ root_cause: str = Field(description="The root cause analysis of the outcome.")
22
+ confidence: float = Field(description="Confidence from 0.0 to 1.0.")
23
+
24
+
25
+ class LLMEvaluator(Evaluator):
26
+ """
27
+ An advanced evaluator that uses an LLM via litellm to deeply analyze experiences.
28
+ Requires litellm and a configured API key for the chosen model.
29
+ """
30
+
31
+ def __init__(self, model: str = "gpt-4o"):
32
+ if not litellm:
33
+ raise EvaluationError(
34
+ "litellm is not installed. Please install experia[llm] or litellm to use the LLMEvaluator."
35
+ )
36
+ self.model = model
37
+ self.system_prompt = (
38
+ "You are an expert cognitive evaluator for an AI agent. "
39
+ "Analyze the given agent's action and its result.\n"
40
+ "1. Identify the root cause of why it succeeded or failed.\n"
41
+ "2. Extract a concise, generalized lesson that the agent should remember for the future.\n"
42
+ "Return the output in valid JSON format matching this schema:\n"
43
+ '{"lesson": "string", "root_cause": "string", "confidence": float}'
44
+ )
45
+
46
+ async def evaluate(self, experience: ExperienceRecord) -> Optional[Lesson]:
47
+ user_prompt = (
48
+ f"Task: {experience.task}\n"
49
+ f"Action Taken: {experience.action}\n"
50
+ f"Result/Outcome: {experience.result}\n"
51
+ f"Active Context: {json.dumps(experience.context)}\n"
52
+ )
53
+
54
+ try:
55
+ response = await litellm.acompletion(
56
+ model=self.model,
57
+ messages=[
58
+ {"role": "system", "content": self.system_prompt},
59
+ {"role": "user", "content": user_prompt},
60
+ ],
61
+ response_format={"type": "json_object"},
62
+ temperature=0.2,
63
+ )
64
+
65
+ raw_content = response.choices[0].message.content
66
+ if not raw_content:
67
+ logger.warning(
68
+ f"LLM returned empty content for experience {experience.id}"
69
+ )
70
+ return None
71
+
72
+ parsed = EvaluatorResponseSchema.model_validate_json(raw_content)
73
+
74
+ logger.info(f"LLM successfully evaluated experience {experience.id}")
75
+ return Lesson(
76
+ experience_id=experience.id,
77
+ content=parsed.lesson,
78
+ root_cause=parsed.root_cause,
79
+ confidence=parsed.confidence,
80
+ )
81
+
82
+ except Exception as e:
83
+ logger.error(
84
+ f"LLMEvaluator failed to evaluate experience {experience.id}: {e}"
85
+ )
86
+ raise EvaluationError(f"LLM evaluation failed: {e}")
@@ -0,0 +1,77 @@
1
+ from datetime import datetime, timezone
2
+ from typing import Any, Dict, Optional
3
+ from uuid import UUID, uuid4
4
+
5
+ from pydantic import BaseModel, Field
6
+
7
+
8
+ class ExperienceRecord(BaseModel):
9
+ """
10
+ Represents a raw experience captured from an agent's execution.
11
+ It logs the exact task, action taken, and the subsequent outcome.
12
+ """
13
+
14
+ id: UUID = Field(
15
+ default_factory=uuid4,
16
+ description="Unique identifier for the experience record.",
17
+ )
18
+ task: str = Field(
19
+ ...,
20
+ description="The high-level task or goal the agent was attempting.",
21
+ json_schema_extra={"example": "Deploy web application"},
22
+ )
23
+ action: str = Field(
24
+ ...,
25
+ description="The specific action or tool call executed.",
26
+ json_schema_extra={"example": "Run command: docker restart nginx"},
27
+ )
28
+ result: str = Field(
29
+ ...,
30
+ description="The raw outcome, error message, or output of the action.",
31
+ json_schema_extra={"example": "Failed: port 80 is already bound."},
32
+ )
33
+ context: Optional[Dict[str, Any]] = Field(
34
+ default_factory=dict,
35
+ description="Optional state variables or memory context active during the action.",
36
+ )
37
+ created_at: datetime = Field(
38
+ default_factory=lambda: datetime.now(timezone.utc),
39
+ description="Timestamp when the experience occurred.",
40
+ )
41
+
42
+
43
+ class Lesson(BaseModel):
44
+ """
45
+ Represents a discrete lesson extracted by the Evaluator engine from an experience.
46
+ """
47
+
48
+ id: UUID = Field(
49
+ default_factory=uuid4, description="Unique identifier for the lesson."
50
+ )
51
+ experience_id: UUID = Field(
52
+ ..., description="The ID of the experience this lesson was derived from."
53
+ )
54
+ content: str = Field(
55
+ ...,
56
+ description="The actual knowledge or rule extracted.",
57
+ json_schema_extra={
58
+ "example": "Always verify port availability using lsof -i :80 before starting the web server."
59
+ },
60
+ )
61
+ root_cause: Optional[str] = Field(
62
+ default=None,
63
+ description="The underlying reason why the action succeeded or failed.",
64
+ json_schema_extra={
65
+ "example": "The port 80 was still bound by an old docker container."
66
+ },
67
+ )
68
+ confidence: float = Field(
69
+ default=0.8,
70
+ ge=0.0,
71
+ le=1.0,
72
+ description="The system's confidence in this lesson (0.0 to 1.0).",
73
+ )
74
+ created_at: datetime = Field(
75
+ default_factory=lambda: datetime.now(timezone.utc),
76
+ description="Timestamp when the lesson was extracted.",
77
+ )
File without changes
@@ -0,0 +1,71 @@
1
+ from typing import Optional
2
+
3
+ from experia.core.interfaces import MemoryStore
4
+ from experia.core.logging import logger
5
+ from experia.experience.models import Lesson
6
+ from experia.memory.models import Memory, MemoryType
7
+
8
+ try:
9
+ import litellm
10
+ except ImportError:
11
+ litellm = None
12
+
13
+
14
+ class RuleGenerator:
15
+ """
16
+ Analyzes lessons and elevates them into permanent behavioral rules using an LLM.
17
+ """
18
+
19
+ def __init__(self, store: MemoryStore, model: str = "gpt-4o"):
20
+ self.store = store
21
+ self.model = model
22
+ self.system_prompt = (
23
+ "You are a cognitive consolidator for an AI agent. "
24
+ "You will be given a recent 'Lesson' the agent learned from an experience. "
25
+ "Determine if this lesson represents a fundamental, reusable behavioral rule "
26
+ "that the agent should ALWAYS follow. "
27
+ "If yes, extract it as a concise, generalized RULE (e.g. 'Always do X before Y'). "
28
+ "If no (it is too specific or trivial), return 'NONE'.\n"
29
+ "Return ONLY the rule string, or 'NONE'."
30
+ )
31
+
32
+ async def consolidate_lesson(self, lesson: Lesson) -> Optional[Memory]:
33
+ """Evaluates a lesson and potentially creates a RULE memory."""
34
+ if not litellm:
35
+ logger.debug("litellm is not installed. Rule generation skipped.")
36
+ return None
37
+
38
+ user_prompt = (
39
+ f"Lesson Content: {lesson.content}\n"
40
+ f"Root Cause: {lesson.root_cause or 'Unknown'}\n"
41
+ )
42
+
43
+ try:
44
+ response = await litellm.acompletion(
45
+ model=self.model,
46
+ messages=[
47
+ {"role": "system", "content": self.system_prompt},
48
+ {"role": "user", "content": user_prompt},
49
+ ],
50
+ temperature=0.1,
51
+ )
52
+
53
+ rule_text = response.choices[0].message.content.strip()
54
+ if not rule_text or rule_text == "NONE":
55
+ logger.debug(f"Lesson {lesson.id} was not elevated to a rule.")
56
+ return None
57
+
58
+ rule_memory = Memory(
59
+ content=rule_text,
60
+ type=MemoryType.RULE,
61
+ importance=1.0, # Rules are highly important
62
+ source=f"Lesson:{lesson.id}",
63
+ )
64
+
65
+ await self.store.save_memory(rule_memory)
66
+ logger.info(f"Generated new RULE from lesson {lesson.id}: {rule_text}")
67
+ return rule_memory
68
+
69
+ except Exception as e:
70
+ logger.error(f"RuleGenerator failed for lesson {lesson.id}: {e}")
71
+ return None
File without changes
File without changes
File without changes
File without changes
File without changes
@@ -0,0 +1,64 @@
1
+ from datetime import datetime, timezone
2
+ from enum import Enum
3
+ from typing import Any, Dict, Optional
4
+ from uuid import UUID, uuid4
5
+
6
+ from pydantic import BaseModel, Field
7
+
8
+
9
+ class MemoryType(str, Enum):
10
+ """Enumeration of the different cognitive types of memory."""
11
+
12
+ FACT = "fact"
13
+ PREFERENCE = "preference"
14
+ LESSON = "lesson"
15
+ RULE = "rule"
16
+ EXPERIENCE = "experience"
17
+
18
+
19
+ class Memory(BaseModel):
20
+ """
21
+ Represents a unit of knowledge stored in the cognitive memory layer.
22
+ """
23
+
24
+ id: UUID = Field(
25
+ default_factory=uuid4, description="Unique identifier for the memory."
26
+ )
27
+ content: str = Field(
28
+ ...,
29
+ description="The actual knowledge stored.",
30
+ json_schema_extra={"example": "User prefers short, concise answers."},
31
+ )
32
+ type: MemoryType = Field(..., description="The category/type of this memory.")
33
+ confidence: float = Field(
34
+ default=0.8,
35
+ ge=0.0,
36
+ le=1.0,
37
+ description="Confidence level in the accuracy of this memory.",
38
+ )
39
+ importance: float = Field(
40
+ default=0.5,
41
+ ge=0.0,
42
+ le=1.0,
43
+ description="Importance weight used for retrieval ranking (0.0 to 1.0).",
44
+ )
45
+ source: Optional[str] = Field(
46
+ default=None,
47
+ description="Where this memory originated from (e.g., user input, experience ID).",
48
+ )
49
+ metadata: Optional[Dict[str, Any]] = Field(
50
+ default_factory=dict,
51
+ description="Additional custom data for advanced filtering.",
52
+ )
53
+
54
+ created_at: datetime = Field(
55
+ default_factory=lambda: datetime.now(timezone.utc),
56
+ description="When the memory was first created.",
57
+ )
58
+ updated_at: datetime = Field(
59
+ default_factory=lambda: datetime.now(timezone.utc),
60
+ description="When the memory was last modified or reinforced.",
61
+ )
62
+ expires_at: Optional[datetime] = Field(
63
+ default=None, description="Optional expiration time for ephemeral memories."
64
+ )
@@ -0,0 +1,224 @@
1
+ import json
2
+ from datetime import datetime
3
+ from typing import List, Optional
4
+ from uuid import UUID
5
+
6
+ import aiosqlite
7
+
8
+ from experia.core.exceptions import StorageError
9
+ from experia.experience.models import ExperienceRecord, Lesson
10
+ from experia.memory.models import Memory, MemoryType
11
+
12
+
13
+ class SQLiteStore:
14
+ """
15
+ An asynchronous SQLite-based local storage backend for Experia.
16
+ Implements the MemoryStore Protocol.
17
+ """
18
+
19
+ def __init__(self, db_path: str = "experia.db"):
20
+ self.db_path = db_path
21
+
22
+ async def initialize(self) -> None:
23
+ """Initializes the database schema if it doesn't exist."""
24
+ try:
25
+ async with aiosqlite.connect(self.db_path) as conn:
26
+ # Experiences Table
27
+ await conn.execute("""
28
+ CREATE TABLE IF NOT EXISTS experiences (
29
+ id TEXT PRIMARY KEY,
30
+ task TEXT NOT NULL,
31
+ action TEXT NOT NULL,
32
+ result TEXT NOT NULL,
33
+ context TEXT,
34
+ created_at TEXT NOT NULL
35
+ )
36
+ """)
37
+
38
+ # Lessons Table
39
+ await conn.execute("""
40
+ CREATE TABLE IF NOT EXISTS lessons (
41
+ id TEXT PRIMARY KEY,
42
+ experience_id TEXT NOT NULL,
43
+ content TEXT NOT NULL,
44
+ root_cause TEXT,
45
+ confidence REAL NOT NULL,
46
+ created_at TEXT NOT NULL,
47
+ FOREIGN KEY (experience_id) REFERENCES experiences (id)
48
+ )
49
+ """)
50
+
51
+ # Check for existing table and add root_cause if missing (migration)
52
+ cursor = await conn.execute("PRAGMA table_info(lessons)")
53
+ columns = [row[1] for row in await cursor.fetchall()]
54
+ if "root_cause" not in columns:
55
+ await conn.execute("ALTER TABLE lessons ADD COLUMN root_cause TEXT")
56
+
57
+ # Memories Table
58
+ await conn.execute("""
59
+ CREATE TABLE IF NOT EXISTS memories (
60
+ id TEXT PRIMARY KEY,
61
+ content TEXT NOT NULL,
62
+ type TEXT NOT NULL,
63
+ confidence REAL NOT NULL,
64
+ importance REAL NOT NULL,
65
+ source TEXT,
66
+ metadata TEXT,
67
+ created_at TEXT NOT NULL,
68
+ updated_at TEXT NOT NULL,
69
+ expires_at TEXT
70
+ )
71
+ """)
72
+ await conn.commit()
73
+ except Exception as e:
74
+ raise StorageError(f"Failed to initialize SQLite database: {e}")
75
+
76
+ # --- Experience Methods ---
77
+
78
+ async def save_experience(self, experience: ExperienceRecord) -> None:
79
+ """Saves a raw experience record asynchronously."""
80
+ try:
81
+ async with aiosqlite.connect(self.db_path) as conn:
82
+ await conn.execute(
83
+ """
84
+ INSERT INTO experiences (id, task, action, result, context, created_at)
85
+ VALUES (?, ?, ?, ?, ?, ?)
86
+ """,
87
+ (
88
+ str(experience.id),
89
+ experience.task,
90
+ experience.action,
91
+ experience.result,
92
+ json.dumps(experience.context) if experience.context else None,
93
+ experience.created_at.isoformat(),
94
+ ),
95
+ )
96
+ await conn.commit()
97
+ except Exception as e:
98
+ raise StorageError(f"Failed to save experience: {e}")
99
+
100
+ async def get_experience(self, experience_id: UUID) -> Optional[ExperienceRecord]:
101
+ """Retrieves an experience by its ID asynchronously."""
102
+ try:
103
+ async with aiosqlite.connect(self.db_path) as conn:
104
+ cursor = await conn.execute(
105
+ "SELECT * FROM experiences WHERE id = ?", (str(experience_id),)
106
+ )
107
+ row = await cursor.fetchone()
108
+
109
+ if row:
110
+ return ExperienceRecord(
111
+ id=UUID(row[0]),
112
+ task=row[1],
113
+ action=row[2],
114
+ result=row[3],
115
+ context=json.loads(row[4]) if row[4] else {},
116
+ created_at=datetime.fromisoformat(row[5]),
117
+ )
118
+ return None
119
+ except Exception as e:
120
+ raise StorageError(f"Failed to retrieve experience: {e}")
121
+
122
+ # --- Lesson Methods ---
123
+
124
+ async def save_lesson(self, lesson: Lesson) -> None:
125
+ """Saves an extracted lesson asynchronously."""
126
+ try:
127
+ async with aiosqlite.connect(self.db_path) as conn:
128
+ await conn.execute(
129
+ """
130
+ INSERT INTO lessons (id, experience_id, content, root_cause, confidence, created_at)
131
+ VALUES (?, ?, ?, ?, ?, ?)
132
+ """,
133
+ (
134
+ str(lesson.id),
135
+ str(lesson.experience_id),
136
+ lesson.content,
137
+ lesson.root_cause,
138
+ lesson.confidence,
139
+ lesson.created_at.isoformat(),
140
+ ),
141
+ )
142
+ await conn.commit()
143
+ except Exception as e:
144
+ raise StorageError(f"Failed to save lesson: {e}")
145
+
146
+ # --- Memory Methods ---
147
+
148
+ async def save_memory(self, memory: Memory) -> None:
149
+ """Saves a memory object asynchronously."""
150
+ try:
151
+ async with aiosqlite.connect(self.db_path) as conn:
152
+ await conn.execute(
153
+ """
154
+ INSERT OR REPLACE INTO memories
155
+ (id, content, type, confidence, importance, source, metadata,
156
+ created_at, updated_at, expires_at)
157
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
158
+ """,
159
+ (
160
+ str(memory.id),
161
+ memory.content,
162
+ memory.type.value,
163
+ memory.confidence,
164
+ memory.importance,
165
+ memory.source,
166
+ json.dumps(memory.metadata) if memory.metadata else None,
167
+ memory.created_at.isoformat(),
168
+ memory.updated_at.isoformat(),
169
+ memory.expires_at.isoformat() if memory.expires_at else None,
170
+ ),
171
+ )
172
+ await conn.commit()
173
+ except Exception as e:
174
+ raise StorageError(f"Failed to save memory: {e}")
175
+
176
+ async def search_memories(
177
+ self,
178
+ query: str = "",
179
+ memory_type: Optional[MemoryType] = None,
180
+ limit: int = 10,
181
+ ) -> List[Memory]:
182
+ """
183
+ Asynchronous simple text-based search for memories.
184
+ """
185
+ memories = []
186
+ try:
187
+ async with aiosqlite.connect(self.db_path) as conn:
188
+ sql = "SELECT * FROM memories WHERE 1=1"
189
+ params = []
190
+
191
+ if query:
192
+ sql += " AND content LIKE ?"
193
+ params.append(f"%{query}%")
194
+
195
+ if memory_type:
196
+ sql += " AND type = ?"
197
+ params.append(memory_type.value)
198
+
199
+ sql += " ORDER BY importance DESC, confidence DESC LIMIT ?"
200
+ params.append(limit)
201
+
202
+ cursor = await conn.execute(sql, tuple(params))
203
+ rows = await cursor.fetchall()
204
+
205
+ for row in rows:
206
+ memories.append(
207
+ Memory(
208
+ id=UUID(row[0]),
209
+ content=row[1],
210
+ type=MemoryType(row[2]),
211
+ confidence=row[3],
212
+ importance=row[4],
213
+ source=row[5],
214
+ metadata=json.loads(row[6]) if row[6] else {},
215
+ created_at=datetime.fromisoformat(row[7]),
216
+ updated_at=datetime.fromisoformat(row[8]),
217
+ expires_at=datetime.fromisoformat(row[9])
218
+ if row[9]
219
+ else None,
220
+ )
221
+ )
222
+ return memories
223
+ except Exception as e:
224
+ raise StorageError(f"Failed to search memories: {e}")
File without changes
File without changes
File without changes
@@ -0,0 +1,102 @@
1
+ Metadata-Version: 2.4
2
+ Name: experia
3
+ Version: 0.2.1
4
+ Summary: The open-source experience learning layer for AI agents.
5
+ Author-email: Experia AI Contributors <hello@experia.ai>
6
+ License: MIT
7
+ License-File: LICENSE
8
+ Requires-Python: >=3.10
9
+ Requires-Dist: aiosqlite>=0.20.0
10
+ Requires-Dist: pydantic>=2.0.0
11
+ Provides-Extra: dev
12
+ Requires-Dist: pytest-asyncio>=0.23.0; extra == 'dev'
13
+ Requires-Dist: pytest>=8.0.0; extra == 'dev'
14
+ Requires-Dist: ruff>=0.4.0; extra == 'dev'
15
+ Provides-Extra: llm
16
+ Requires-Dist: litellm>=1.0.0; extra == 'llm'
17
+ Description-Content-Type: text/markdown
18
+
19
+ # Experia AI
20
+
21
+ The open-source experience learning layer for AI agents.
22
+
23
+ Experia enables agents to learn from past actions, failures, and outcomes.
24
+ It provides experience capture, lesson extraction, behavioral improvement,
25
+ and long-term cognitive memory without replacing existing agent frameworks.
26
+
27
+ ## Vision
28
+
29
+ Current AI agents start from zero on every interaction. Experia adds an **experience learning loop** around agents. It allows agents to remember what happened, understand why it worked or failed, and improve future decisions.
30
+
31
+ **Observation → Action → Result → Experience → Lesson → Memory → Better Future Action**
32
+
33
+ ```mermaid
34
+ flowchart TD
35
+ subgraph Agent Application
36
+ Agent[AI Agent / LLM]
37
+ Task[Execute Task]
38
+ Agent -- Takes Action --> Task
39
+ end
40
+
41
+ subgraph Experia AI Cognitive Layer [Experia Async Cognitive Layer]
42
+ Store[(MemoryStore Protocol)]
43
+ Eval[Evaluator Protocol]
44
+ Ctx[Context Builder]
45
+
46
+ Task -- 1. await record() --> Store
47
+ Store -- 2. Analyze Experience --> Eval
48
+ Eval -- 3. Extract Lesson --> Store
49
+ Store -- 4. await retrieve_context() --> Ctx
50
+ end
51
+
52
+ Ctx -- 5. Inject Knowledge --> Agent
53
+ ```
54
+
55
+ ## Integrations
56
+
57
+ Experia acts as a cognitive plugin. It does not replace your agent frameworks (like LangChain, AutoGen, CrewAI), it enhances them by managing long-term memory, learned experiences, user knowledge, and behavioral patterns.
58
+
59
+ ## Getting Started
60
+
61
+ Experia uses an **asynchronous** and **pluggable** architecture.
62
+
63
+ ```bash
64
+ pip install experia
65
+ ```
66
+
67
+ ```python
68
+ import asyncio
69
+ from experia.core.learner import Learner
70
+ from experia.memory.store import SQLiteStore
71
+ from experia.experience.evaluator import SimpleHeuristicEvaluator
72
+
73
+
74
+ async def main():
75
+ # 1. Dependency Injection setup
76
+ store = SQLiteStore("my_agent.db")
77
+ await store.initialize()
78
+
79
+ evaluator = SimpleHeuristicEvaluator()
80
+
81
+ # 2. Initialize Learner
82
+ agent = Learner(store=store, evaluator=evaluator)
83
+
84
+ # 3. Use the async API to record actions
85
+ await agent.record(
86
+ task="Deploy web app",
87
+ action="Restart Nginx",
88
+ result="failed with config syntax error",
89
+ )
90
+
91
+ # 4. Retrieve memory context for your LLM
92
+ context = await agent.retrieve_context()
93
+ print(context)
94
+
95
+
96
+ if __name__ == "__main__":
97
+ asyncio.run(main())
98
+ ```
99
+
100
+ ## License
101
+
102
+ This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
@@ -0,0 +1,34 @@
1
+ experia/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ experia/adapters/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ experia/adapters/mem0.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ experia/adapters/postgres.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ experia/adapters/zep.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ experia/context/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ experia/context/builder.py,sha256=b1Q2WHyb6Z5bskqqY8QXPDy640EBYixR08RA9yAfz3c,1044
8
+ experia/core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ experia/core/exceptions.py,sha256=9DjA6BTXxPf--_8d5bNe-8CP2LX1eBcFm_V0_qSPKoY,388
10
+ experia/core/interfaces.py,sha256=4-2mIhSmwxIPIk6GAkdjsD1aBqhnjP-fktErafDuvn8,920
11
+ experia/core/learner.py,sha256=6nrUQXduu8O0RDj_ATBTAoTkZaoY2Cug1GpfBJ_v9PM,3356
12
+ experia/core/logging.py,sha256=ogjeDG2oqKhpdI1xmJlbT8tztr_H5V9q9bGK7EGKLno,508
13
+ experia/experience/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
14
+ experia/experience/collector.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
15
+ experia/experience/evaluator.py,sha256=L55SaurrtfJVd5-ttWpp3dEKm7ay5_pyExP1J0uX10Q,1472
16
+ experia/experience/lessons.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
17
+ experia/experience/llm_evaluator.py,sha256=hBw6d_Tx0ONcq_a1kzgYpnuAaXFQBOxVRJ7cljSooZ4,3228
18
+ experia/experience/models.py,sha256=5YVkr9qTYmqF5jLpymDGB-BwlYG858DpeeZz1mBO2VE,2585
19
+ experia/improvement/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
20
+ experia/improvement/rules.py,sha256=bj3i85NlRUb8Dkrk4wjAI-Z-4eAXVMdDbdlNrn4Tx7k,2594
21
+ experia/improvement/strategies.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
22
+ experia/integrations/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
23
+ experia/integrations/langchain.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
24
+ experia/integrations/langgraph.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
25
+ experia/memory/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
26
+ experia/memory/models.py,sha256=k6GBTmbvMCO3NMwQuo0ftUHlMI_zGmbxo0QlxCHvUnE,1977
27
+ experia/memory/store.py,sha256=Nl6QMuL2sq7vMWsn1Pzksy2Mh-DdJxa4EQNL_2Ew3eE,8762
28
+ experia/reflection/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
29
+ experia/reflection/conflict.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
30
+ experia/reflection/consolidation.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
31
+ experia-0.2.1.dist-info/METADATA,sha256=0T6QaqSnVsExk_vMo7u38gVJ05R8BqsalHTpj77KP2Q,3043
32
+ experia-0.2.1.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
33
+ experia-0.2.1.dist-info/licenses/LICENSE,sha256=EXGi_NZXQyjN9a23PCxw4Gmy4HrUviDJpsfHslDgn4Q,1080
34
+ experia-0.2.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Experia AI Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.