This commit is contained in:
Nicolò Boschi 2025-11-19 16:28:02 +01:00
parent aa35223056
commit 99a54aec90
205 changed files with 17773 additions and 7901 deletions

View file

@ -448,8 +448,6 @@ configure(
agent_id="my-agent", # Agent identifier (required) agent_id="my-agent", # Agent identifier (required)
store_conversations=True, # Store conversations store_conversations=True, # Store conversations
inject_memories=True, # Inject memories inject_memories=True, # Inject memories
memory_search_budget=10, # Number of memories to retrieve
context_window=10, # Conversation history size
document_id="session-123", # Optional: Group conversations by document ID document_id="session-123", # Optional: Group conversations by document ID
enabled=True, # Master switch enabled=True, # Master switch
) )

View file

@ -0,0 +1,132 @@
# OpenAPI Client Generator Comparison
## Current: openapi-python-client
**Pros:**
- Python-native (no Java required)
- Lightweight
- Good type hints
- Uses httpx (modern)
**Cons:**
- Functional style (not OOP)
- Verbose imports
- Awkward API (need to pass client everywhere)
## Option 1: openapi-generator (Recommended)
**Command:** `openapi-generator-cli generate -i openapi.json -g python -o memora-clients/python`
**Pros:**
- ✅ **OOP style** - generates `client.search_memories()` not `search_memories.sync(client=...)`
- ✅ Widely used (industry standard)
- ✅ Active development
- ✅ Generates proper SDK with clean imports
- ✅ Built-in retry, timeout handling
**Cons:**
- Requires Java Runtime (but can use Docker)
- Larger generated code
- Some boilerplate
**Example Generated Code:**
```python
from memora_client import ApiClient, Configuration, MemoryOperationsApi
config = Configuration(host="http://localhost:8000")
client = ApiClient(config)
api = MemoryOperationsApi(client)
# Clean method calls!
results = api.search_memories(
agent_id="alice",
search_request=SearchRequest(query="...")
)
```
## Option 2: fern
**Command:** `fern generate`
**Pros:**
- ✅ Modern, best-in-class DX
- ✅ Beautiful generated code
- ✅ Excellent type hints
- ✅ Async-first
- ✅ Pydantic v2 models
**Cons:**
- Requires `fern.config.yml` setup
- Less mature than openapi-generator
- Config-heavy
**Example:**
```python
from memora import Memora
client = Memora(base_url="http://localhost:8000")
results = client.search_memories(agent_id="alice", query="...")
```
## Option 3: speakeasy
**Command:** `speakeasy generate sdk`
**Pros:**
- ✅ Very clean generated code
- ✅ Great DX
- ✅ SDK versioning built-in
**Cons:**
- Commercial (free tier available)
- Requires account
- Less control
## Recommendation: openapi-generator
Use **openapi-generator** because it:
1. Generates proper OOP-style APIs
2. Industry standard with great support
3. Can run via Docker (no Java install needed)
4. Will give you `api.search_memories()` style calls
### Migration Steps:
1. **Install via Docker:**
```bash
alias openapi-generator='docker run --rm -v "${PWD}:/local" openapitools/openapi-generator-cli'
```
2. **Generate config:**
```bash
openapi-generator config-help -g python
```
3. **Create config file:** `openapi-generator-config.yaml`
```yaml
packageName: memora_client
projectName: memora-client
packageVersion: 0.0.7
library: urllib3 # or 'asyncio' for async
```
4. **Generate:**
```bash
openapi-generator generate \
-i openapi.json \
-g python \
-o memora-clients/python \
-c openapi-generator-config.yaml
```
This will generate code like:
```python
import memora_client
from memora_client.api import memory_operations_api
config = memora_client.Configuration(host="http://localhost:8000")
with memora_client.ApiClient(config) as api_client:
api = memory_operations_api.MemoryOperationsApi(api_client)
response = api.search_memories(
agent_id="alice",
search_request=SearchRequest(query="...")
)
```
Then we add our thin `Memora` wrapper on top for even simpler usage!

View file

@ -1,23 +0,0 @@
__pycache__/
build/
dist/
*.egg-info/
.pytest_cache/
# pyenv
.python-version
# Environments
.env
.venv
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# JetBrains
.idea/
/coverage.xml
/.coverage

View file

@ -0,0 +1,23 @@
# OpenAPI Generator Ignore
# Generated by openapi-generator https://github.com/openapitools/openapi-generator
# Use this file to prevent files from being overwritten by the generator.
# The patterns follow closely to .gitignore or .dockerignore.
# As an example, the C# client generator defines ApiClient.cs.
# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line:
#ApiClient.cs
# You can match any string of characters against a directory, file or extension with a single asterisk (*):
#foo/*/qux
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
#foo/**/qux
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
# You can also negate patterns with an exclamation (!).
# For example, you can ignore all files in a docs folder with the file extension .md:
#docs/*.md
# Then explicitly reverse the ignore rule for a single file:
#!docs/README.md

View file

@ -0,0 +1,103 @@
memora_client_api/__init__.py
memora_client_api/api/__init__.py
memora_client_api/api/agent_management_api.py
memora_client_api/api/documents_api.py
memora_client_api/api/memory_operations_api.py
memora_client_api/api/reasoning_api.py
memora_client_api/api/visualization_api.py
memora_client_api/api_client.py
memora_client_api/api_response.py
memora_client_api/configuration.py
memora_client_api/docs/AddBackgroundRequest.md
memora_client_api/docs/AgentListItem.md
memora_client_api/docs/AgentListResponse.md
memora_client_api/docs/AgentManagementApi.md
memora_client_api/docs/AgentProfileResponse.md
memora_client_api/docs/BackgroundResponse.md
memora_client_api/docs/BatchPutAsyncResponse.md
memora_client_api/docs/BatchPutRequest.md
memora_client_api/docs/BatchPutResponse.md
memora_client_api/docs/CreateAgentRequest.md
memora_client_api/docs/DeleteResponse.md
memora_client_api/docs/DocumentResponse.md
memora_client_api/docs/DocumentsApi.md
memora_client_api/docs/GraphDataResponse.md
memora_client_api/docs/HTTPValidationError.md
memora_client_api/docs/ListDocumentsResponse.md
memora_client_api/docs/ListMemoryUnitsResponse.md
memora_client_api/docs/MemoryItem.md
memora_client_api/docs/MemoryOperationsApi.md
memora_client_api/docs/PersonalityTraits.md
memora_client_api/docs/ReasoningApi.md
memora_client_api/docs/SearchRequest.md
memora_client_api/docs/SearchResponse.md
memora_client_api/docs/SearchResult.md
memora_client_api/docs/ThinkFact.md
memora_client_api/docs/ThinkRequest.md
memora_client_api/docs/ThinkResponse.md
memora_client_api/docs/UpdatePersonalityRequest.md
memora_client_api/docs/ValidationError.md
memora_client_api/docs/ValidationErrorLocInner.md
memora_client_api/docs/VisualizationApi.md
memora_client_api/exceptions.py
memora_client_api/models/__init__.py
memora_client_api/models/add_background_request.py
memora_client_api/models/agent_list_item.py
memora_client_api/models/agent_list_response.py
memora_client_api/models/agent_profile_response.py
memora_client_api/models/background_response.py
memora_client_api/models/batch_put_async_response.py
memora_client_api/models/batch_put_request.py
memora_client_api/models/batch_put_response.py
memora_client_api/models/create_agent_request.py
memora_client_api/models/delete_response.py
memora_client_api/models/document_response.py
memora_client_api/models/graph_data_response.py
memora_client_api/models/http_validation_error.py
memora_client_api/models/list_documents_response.py
memora_client_api/models/list_memory_units_response.py
memora_client_api/models/memory_item.py
memora_client_api/models/personality_traits.py
memora_client_api/models/search_request.py
memora_client_api/models/search_response.py
memora_client_api/models/search_result.py
memora_client_api/models/think_fact.py
memora_client_api/models/think_request.py
memora_client_api/models/think_response.py
memora_client_api/models/update_personality_request.py
memora_client_api/models/validation_error.py
memora_client_api/models/validation_error_loc_inner.py
memora_client_api/rest.py
memora_client_api/test/__init__.py
memora_client_api/test/test_add_background_request.py
memora_client_api/test/test_agent_list_item.py
memora_client_api/test/test_agent_list_response.py
memora_client_api/test/test_agent_management_api.py
memora_client_api/test/test_agent_profile_response.py
memora_client_api/test/test_background_response.py
memora_client_api/test/test_batch_put_async_response.py
memora_client_api/test/test_batch_put_request.py
memora_client_api/test/test_batch_put_response.py
memora_client_api/test/test_create_agent_request.py
memora_client_api/test/test_delete_response.py
memora_client_api/test/test_document_response.py
memora_client_api/test/test_documents_api.py
memora_client_api/test/test_graph_data_response.py
memora_client_api/test/test_http_validation_error.py
memora_client_api/test/test_list_documents_response.py
memora_client_api/test/test_list_memory_units_response.py
memora_client_api/test/test_memory_item.py
memora_client_api/test/test_memory_operations_api.py
memora_client_api/test/test_personality_traits.py
memora_client_api/test/test_reasoning_api.py
memora_client_api/test/test_search_request.py
memora_client_api/test/test_search_response.py
memora_client_api/test/test_search_result.py
memora_client_api/test/test_think_fact.py
memora_client_api/test/test_think_request.py
memora_client_api/test/test_think_response.py
memora_client_api/test/test_update_personality_request.py
memora_client_api/test/test_validation_error.py
memora_client_api/test/test_validation_error_loc_inner.py
memora_client_api/test/test_visualization_api.py
memora_client_api_README.md

View file

@ -0,0 +1 @@
7.18.0-SNAPSHOT

View file

@ -1,8 +1,6 @@
# memora-client # Memora Python Client
Python client for Memora - Semantic memory system with personality-driven thinking. Clean, pythonic client for the Memora API - A semantic memory system with personality-driven thinking.
**Auto-generated from OpenAPI spec** - provides type-safe access to all Memora API endpoints.
## Installation ## Installation
@ -13,67 +11,124 @@ pip install memora-client
## Quick Start ## Quick Start
```python ```python
from agent_memory_api_client import Client from memora_client import Memora
from agent_memory_api_client.api.memory_storage import put_api_put_post
from agent_memory_api_client.api.reasoning import think_api_think_post
client = Client(base_url="http://localhost:8000") # Initialize client
client = Memora(base_url="http://localhost:8000")
# Store memory # Store a memory
put_api_put_post.sync( client.store(agent_id="alice", content="Alice loves artificial intelligence")
client=client,
body={
"agent_id": "user123",
"content": "Alice loves machine learning"
}
)
# Think (generate answer with personality) # Search memories
response = think_api_think_post.sync( results = client.search(agent_id="alice", query="What does Alice like?")
client=client, print(results)
body={
"agent_id": "user123", # Generate contextual answer
"query": "What does Alice think about AI?", answer = client.think(agent_id="alice", query="What are my interests?")
"thinking_budget": 50 print(answer["text"])
}
)
print(response.text)
``` ```
## Async Support ## Main Operations
### Store Memories
```python ```python
from agent_memory_api_client import Client # Store a single memory
from agent_memory_api_client.api.reasoning import think_api_think_post client.store(
agent_id="alice",
content="Alice completed a Python project using FastAPI",
event_date=datetime(2024, 1, 15),
context="work projects"
)
async with Client(base_url="http://localhost:8000") as client: # Store multiple memories in batch
response = await think_api_think_post.asyncio( client.store_batch(
client=client, agent_id="alice",
body={ items=[
"agent_id": "user123", {"content": "Alice loves machine learning"},
"query": "What does Alice think about AI?" {"content": "Bob enjoys hiking", "event_date": datetime(2024, 10, 15)},
} ]
) )
print(response.text)
``` ```
## API Modules ### Search Memories
This client provides access to: ```python
- `memory_storage` - Store and retrieve facts # Simple search
- `search` - Semantic and temporal search results = client.search(
- `reasoning` - Personality-driven thinking agent_id="alice",
- `visualization` - Memory graphs and statistics query="What does Alice like?",
- `management` - Agent profiles and configuration max_tokens=2048
- `documents` - Document tracking )
See auto-generated code for full API surface and type hints. # Advanced search with all options
response = client.search_memories(
agent_id="alice",
query="What are Alice's interests?",
fact_type=["world"],
max_tokens=4096,
trace=True # Include trace information
)
```
### Think (Generate Contextual Answers)
```python
answer = client.think(
agent_id="alice",
query="What should I focus on learning next?",
thinking_budget=100,
context="I want to advance my career in AI"
)
print(answer["text"]) # The generated answer
print(answer["based_on"]) # Facts used to generate the answer
```
## Structure
```
memora-client/
├── memora_client/ # Maintained wrapper (simple API)
│ ├── __init__.py
│ ├── memora_client.py # Clean interface: store(), search(), think()
│ └── tests/
│ └── test_main_operations.py
└── memora_client_api/ # Auto-generated from OpenAPI spec
├── api/ # Full API operations
├── models/ # Request/response models
└── ...
```
## Testing
Run integration tests (requires running Memora API server):
```bash
# Set API URL (optional, defaults to http://localhost:8000)
export MEMORA_API_URL=http://localhost:8000
# Run tests
pytest memora_client/tests/test_main_operations.py -v
```
## Development ## Development
Auto-generated from `openapi.json`. See [RELEASE.md](../../RELEASE.md) for regeneration instructions. ### Regenerate Client
## Links The low-level API client is auto-generated from the OpenAPI spec. The high-level wrapper (`memora_client/`) is maintained and won't be overwritten.
- [GitHub Repository](https://github.com/nicoloboschi/memora) ```bash
- [Full Documentation](https://github.com/nicoloboschi/memora/blob/main/README.md) # Regenerate from OpenAPI spec
./scripts/generate-clients.sh
```
This preserves:
- `memora_client/` - Maintained wrapper
- `pyproject.toml` - Package configuration
- Tests and documentation
## License
Apache 2.0

View file

@ -1,8 +0,0 @@
"""A client library for accessing Agent Memory API"""
from .client import AuthenticatedClient, Client
__all__ = (
"AuthenticatedClient",
"Client",
)

View file

@ -1 +0,0 @@
"""Contains methods for accessing the API"""

View file

@ -1 +0,0 @@
"""Contains endpoint functions for accessing the API"""

View file

@ -1,195 +0,0 @@
from http import HTTPStatus
from typing import Any
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.add_background_request import AddBackgroundRequest
from ...models.background_response import BackgroundResponse
from ...models.http_validation_error import HTTPValidationError
from ...types import Response
def _get_kwargs(
agent_id: str,
*,
body: AddBackgroundRequest,
) -> dict[str, Any]:
headers: dict[str, Any] = {}
_kwargs: dict[str, Any] = {
"method": "post",
"url": f"/api/v1/agents/{agent_id}/background",
}
_kwargs["json"] = body.to_dict()
headers["Content-Type"] = "application/json"
_kwargs["headers"] = headers
return _kwargs
def _parse_response(
*, client: AuthenticatedClient | Client, response: httpx.Response
) -> BackgroundResponse | HTTPValidationError | None:
if response.status_code == 200:
response_200 = BackgroundResponse.from_dict(response.json())
return response_200
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: AuthenticatedClient | Client, response: httpx.Response
) -> Response[BackgroundResponse | HTTPValidationError]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
agent_id: str,
*,
client: AuthenticatedClient | Client,
body: AddBackgroundRequest,
) -> Response[BackgroundResponse | HTTPValidationError]:
"""Add/merge agent background
Add new background information or merge with existing. LLM intelligently resolves conflicts,
normalizes to first person, and optionally infers personality traits.
Args:
agent_id (str):
body (AddBackgroundRequest): Request model for adding/merging background information.
Example: {'content': 'I was born in Texas', 'update_personality': True}.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[BackgroundResponse | HTTPValidationError]
"""
kwargs = _get_kwargs(
agent_id=agent_id,
body=body,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
agent_id: str,
*,
client: AuthenticatedClient | Client,
body: AddBackgroundRequest,
) -> BackgroundResponse | HTTPValidationError | None:
"""Add/merge agent background
Add new background information or merge with existing. LLM intelligently resolves conflicts,
normalizes to first person, and optionally infers personality traits.
Args:
agent_id (str):
body (AddBackgroundRequest): Request model for adding/merging background information.
Example: {'content': 'I was born in Texas', 'update_personality': True}.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
BackgroundResponse | HTTPValidationError
"""
return sync_detailed(
agent_id=agent_id,
client=client,
body=body,
).parsed
async def asyncio_detailed(
agent_id: str,
*,
client: AuthenticatedClient | Client,
body: AddBackgroundRequest,
) -> Response[BackgroundResponse | HTTPValidationError]:
"""Add/merge agent background
Add new background information or merge with existing. LLM intelligently resolves conflicts,
normalizes to first person, and optionally infers personality traits.
Args:
agent_id (str):
body (AddBackgroundRequest): Request model for adding/merging background information.
Example: {'content': 'I was born in Texas', 'update_personality': True}.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[BackgroundResponse | HTTPValidationError]
"""
kwargs = _get_kwargs(
agent_id=agent_id,
body=body,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
agent_id: str,
*,
client: AuthenticatedClient | Client,
body: AddBackgroundRequest,
) -> BackgroundResponse | HTTPValidationError | None:
"""Add/merge agent background
Add new background information or merge with existing. LLM intelligently resolves conflicts,
normalizes to first person, and optionally infers personality traits.
Args:
agent_id (str):
body (AddBackgroundRequest): Request model for adding/merging background information.
Example: {'content': 'I was born in Texas', 'update_personality': True}.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
BackgroundResponse | HTTPValidationError
"""
return (
await asyncio_detailed(
agent_id=agent_id,
client=client,
body=body,
)
).parsed

View file

@ -1,131 +0,0 @@
from http import HTTPStatus
from typing import Any
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.agent_list_response import AgentListResponse
from ...types import Response
def _get_kwargs() -> dict[str, Any]:
_kwargs: dict[str, Any] = {
"method": "get",
"url": "/api/v1/agents",
}
return _kwargs
def _parse_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> AgentListResponse | None:
if response.status_code == 200:
response_200 = AgentListResponse.from_dict(response.json())
return response_200
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> Response[AgentListResponse]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
*,
client: AuthenticatedClient | Client,
) -> Response[AgentListResponse]:
"""List all agents
Get a list of all agents with their profiles
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[AgentListResponse]
"""
kwargs = _get_kwargs()
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
*,
client: AuthenticatedClient | Client,
) -> AgentListResponse | None:
"""List all agents
Get a list of all agents with their profiles
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
AgentListResponse
"""
return sync_detailed(
client=client,
).parsed
async def asyncio_detailed(
*,
client: AuthenticatedClient | Client,
) -> Response[AgentListResponse]:
"""List all agents
Get a list of all agents with their profiles
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[AgentListResponse]
"""
kwargs = _get_kwargs()
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
*,
client: AuthenticatedClient | Client,
) -> AgentListResponse | None:
"""List all agents
Get a list of all agents with their profiles
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
AgentListResponse
"""
return (
await asyncio_detailed(
client=client,
)
).parsed

View file

@ -1,203 +0,0 @@
from http import HTTPStatus
from typing import Any
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.agent_profile_response import AgentProfileResponse
from ...models.create_agent_request import CreateAgentRequest
from ...models.http_validation_error import HTTPValidationError
from ...types import Response
def _get_kwargs(
agent_id: str,
*,
body: CreateAgentRequest,
) -> dict[str, Any]:
headers: dict[str, Any] = {}
_kwargs: dict[str, Any] = {
"method": "put",
"url": f"/api/v1/agents/{agent_id}",
}
_kwargs["json"] = body.to_dict()
headers["Content-Type"] = "application/json"
_kwargs["headers"] = headers
return _kwargs
def _parse_response(
*, client: AuthenticatedClient | Client, response: httpx.Response
) -> AgentProfileResponse | HTTPValidationError | None:
if response.status_code == 200:
response_200 = AgentProfileResponse.from_dict(response.json())
return response_200
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: AuthenticatedClient | Client, response: httpx.Response
) -> Response[AgentProfileResponse | HTTPValidationError]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
agent_id: str,
*,
client: AuthenticatedClient | Client,
body: CreateAgentRequest,
) -> Response[AgentProfileResponse | HTTPValidationError]:
"""Create or update agent
Create a new agent or update existing agent with personality and background. Auto-fills missing
fields with defaults.
Args:
agent_id (str):
body (CreateAgentRequest): Request model for creating/updating an agent. Example:
{'background': 'I am a creative software engineer with 10 years of experience',
'personality': {'agreeableness': 0.7, 'bias_strength': 0.7, 'conscientiousness': 0.6,
'extraversion': 0.5, 'neuroticism': 0.3, 'openness': 0.8}}.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[AgentProfileResponse | HTTPValidationError]
"""
kwargs = _get_kwargs(
agent_id=agent_id,
body=body,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
agent_id: str,
*,
client: AuthenticatedClient | Client,
body: CreateAgentRequest,
) -> AgentProfileResponse | HTTPValidationError | None:
"""Create or update agent
Create a new agent or update existing agent with personality and background. Auto-fills missing
fields with defaults.
Args:
agent_id (str):
body (CreateAgentRequest): Request model for creating/updating an agent. Example:
{'background': 'I am a creative software engineer with 10 years of experience',
'personality': {'agreeableness': 0.7, 'bias_strength': 0.7, 'conscientiousness': 0.6,
'extraversion': 0.5, 'neuroticism': 0.3, 'openness': 0.8}}.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
AgentProfileResponse | HTTPValidationError
"""
return sync_detailed(
agent_id=agent_id,
client=client,
body=body,
).parsed
async def asyncio_detailed(
agent_id: str,
*,
client: AuthenticatedClient | Client,
body: CreateAgentRequest,
) -> Response[AgentProfileResponse | HTTPValidationError]:
"""Create or update agent
Create a new agent or update existing agent with personality and background. Auto-fills missing
fields with defaults.
Args:
agent_id (str):
body (CreateAgentRequest): Request model for creating/updating an agent. Example:
{'background': 'I am a creative software engineer with 10 years of experience',
'personality': {'agreeableness': 0.7, 'bias_strength': 0.7, 'conscientiousness': 0.6,
'extraversion': 0.5, 'neuroticism': 0.3, 'openness': 0.8}}.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[AgentProfileResponse | HTTPValidationError]
"""
kwargs = _get_kwargs(
agent_id=agent_id,
body=body,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
agent_id: str,
*,
client: AuthenticatedClient | Client,
body: CreateAgentRequest,
) -> AgentProfileResponse | HTTPValidationError | None:
"""Create or update agent
Create a new agent or update existing agent with personality and background. Auto-fills missing
fields with defaults.
Args:
agent_id (str):
body (CreateAgentRequest): Request model for creating/updating an agent. Example:
{'background': 'I am a creative software engineer with 10 years of experience',
'personality': {'agreeableness': 0.7, 'bias_strength': 0.7, 'conscientiousness': 0.6,
'extraversion': 0.5, 'neuroticism': 0.3, 'openness': 0.8}}.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
AgentProfileResponse | HTTPValidationError
"""
return (
await asyncio_detailed(
agent_id=agent_id,
client=client,
body=body,
)
).parsed

View file

@ -1,165 +0,0 @@
from http import HTTPStatus
from typing import Any
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.agent_profile_response import AgentProfileResponse
from ...models.http_validation_error import HTTPValidationError
from ...types import Response
def _get_kwargs(
agent_id: str,
) -> dict[str, Any]:
_kwargs: dict[str, Any] = {
"method": "get",
"url": f"/api/v1/agents/{agent_id}/profile",
}
return _kwargs
def _parse_response(
*, client: AuthenticatedClient | Client, response: httpx.Response
) -> AgentProfileResponse | HTTPValidationError | None:
if response.status_code == 200:
response_200 = AgentProfileResponse.from_dict(response.json())
return response_200
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: AuthenticatedClient | Client, response: httpx.Response
) -> Response[AgentProfileResponse | HTTPValidationError]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
agent_id: str,
*,
client: AuthenticatedClient | Client,
) -> Response[AgentProfileResponse | HTTPValidationError]:
"""Get agent profile
Get personality traits and background for an agent. Auto-creates agent with defaults if not exists.
Args:
agent_id (str):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[AgentProfileResponse | HTTPValidationError]
"""
kwargs = _get_kwargs(
agent_id=agent_id,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
agent_id: str,
*,
client: AuthenticatedClient | Client,
) -> AgentProfileResponse | HTTPValidationError | None:
"""Get agent profile
Get personality traits and background for an agent. Auto-creates agent with defaults if not exists.
Args:
agent_id (str):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
AgentProfileResponse | HTTPValidationError
"""
return sync_detailed(
agent_id=agent_id,
client=client,
).parsed
async def asyncio_detailed(
agent_id: str,
*,
client: AuthenticatedClient | Client,
) -> Response[AgentProfileResponse | HTTPValidationError]:
"""Get agent profile
Get personality traits and background for an agent. Auto-creates agent with defaults if not exists.
Args:
agent_id (str):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[AgentProfileResponse | HTTPValidationError]
"""
kwargs = _get_kwargs(
agent_id=agent_id,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
agent_id: str,
*,
client: AuthenticatedClient | Client,
) -> AgentProfileResponse | HTTPValidationError | None:
"""Get agent profile
Get personality traits and background for an agent. Auto-creates agent with defaults if not exists.
Args:
agent_id (str):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
AgentProfileResponse | HTTPValidationError
"""
return (
await asyncio_detailed(
agent_id=agent_id,
client=client,
)
).parsed

View file

@ -1,163 +0,0 @@
from http import HTTPStatus
from typing import Any
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.http_validation_error import HTTPValidationError
from ...types import Response
def _get_kwargs(
agent_id: str,
) -> dict[str, Any]:
_kwargs: dict[str, Any] = {
"method": "get",
"url": f"/api/v1/agents/{agent_id}/stats",
}
return _kwargs
def _parse_response(
*, client: AuthenticatedClient | Client, response: httpx.Response
) -> Any | HTTPValidationError | None:
if response.status_code == 200:
response_200 = response.json()
return response_200
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: AuthenticatedClient | Client, response: httpx.Response
) -> Response[Any | HTTPValidationError]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
agent_id: str,
*,
client: AuthenticatedClient | Client,
) -> Response[Any | HTTPValidationError]:
"""Get memory statistics for an agent
Get statistics about nodes and links for a specific agent
Args:
agent_id (str):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Any | HTTPValidationError]
"""
kwargs = _get_kwargs(
agent_id=agent_id,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
agent_id: str,
*,
client: AuthenticatedClient | Client,
) -> Any | HTTPValidationError | None:
"""Get memory statistics for an agent
Get statistics about nodes and links for a specific agent
Args:
agent_id (str):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Any | HTTPValidationError
"""
return sync_detailed(
agent_id=agent_id,
client=client,
).parsed
async def asyncio_detailed(
agent_id: str,
*,
client: AuthenticatedClient | Client,
) -> Response[Any | HTTPValidationError]:
"""Get memory statistics for an agent
Get statistics about nodes and links for a specific agent
Args:
agent_id (str):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Any | HTTPValidationError]
"""
kwargs = _get_kwargs(
agent_id=agent_id,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
agent_id: str,
*,
client: AuthenticatedClient | Client,
) -> Any | HTTPValidationError | None:
"""Get memory statistics for an agent
Get statistics about nodes and links for a specific agent
Args:
agent_id (str):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Any | HTTPValidationError
"""
return (
await asyncio_detailed(
agent_id=agent_id,
client=client,
)
).parsed

View file

@ -1,187 +0,0 @@
from http import HTTPStatus
from typing import Any
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.agent_profile_response import AgentProfileResponse
from ...models.http_validation_error import HTTPValidationError
from ...models.update_personality_request import UpdatePersonalityRequest
from ...types import Response
def _get_kwargs(
agent_id: str,
*,
body: UpdatePersonalityRequest,
) -> dict[str, Any]:
headers: dict[str, Any] = {}
_kwargs: dict[str, Any] = {
"method": "put",
"url": f"/api/v1/agents/{agent_id}/profile",
}
_kwargs["json"] = body.to_dict()
headers["Content-Type"] = "application/json"
_kwargs["headers"] = headers
return _kwargs
def _parse_response(
*, client: AuthenticatedClient | Client, response: httpx.Response
) -> AgentProfileResponse | HTTPValidationError | None:
if response.status_code == 200:
response_200 = AgentProfileResponse.from_dict(response.json())
return response_200
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: AuthenticatedClient | Client, response: httpx.Response
) -> Response[AgentProfileResponse | HTTPValidationError]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
agent_id: str,
*,
client: AuthenticatedClient | Client,
body: UpdatePersonalityRequest,
) -> Response[AgentProfileResponse | HTTPValidationError]:
"""Update agent personality
Update agent's Big Five personality traits and bias strength
Args:
agent_id (str):
body (UpdatePersonalityRequest): Request model for updating personality traits.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[AgentProfileResponse | HTTPValidationError]
"""
kwargs = _get_kwargs(
agent_id=agent_id,
body=body,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
agent_id: str,
*,
client: AuthenticatedClient | Client,
body: UpdatePersonalityRequest,
) -> AgentProfileResponse | HTTPValidationError | None:
"""Update agent personality
Update agent's Big Five personality traits and bias strength
Args:
agent_id (str):
body (UpdatePersonalityRequest): Request model for updating personality traits.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
AgentProfileResponse | HTTPValidationError
"""
return sync_detailed(
agent_id=agent_id,
client=client,
body=body,
).parsed
async def asyncio_detailed(
agent_id: str,
*,
client: AuthenticatedClient | Client,
body: UpdatePersonalityRequest,
) -> Response[AgentProfileResponse | HTTPValidationError]:
"""Update agent personality
Update agent's Big Five personality traits and bias strength
Args:
agent_id (str):
body (UpdatePersonalityRequest): Request model for updating personality traits.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[AgentProfileResponse | HTTPValidationError]
"""
kwargs = _get_kwargs(
agent_id=agent_id,
body=body,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
agent_id: str,
*,
client: AuthenticatedClient | Client,
body: UpdatePersonalityRequest,
) -> AgentProfileResponse | HTTPValidationError | None:
"""Update agent personality
Update agent's Big Five personality traits and bias strength
Args:
agent_id (str):
body (UpdatePersonalityRequest): Request model for updating personality traits.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
AgentProfileResponse | HTTPValidationError
"""
return (
await asyncio_detailed(
agent_id=agent_id,
client=client,
body=body,
)
).parsed

View file

@ -1 +0,0 @@
"""Contains endpoint functions for accessing the API"""

View file

@ -1,178 +0,0 @@
from http import HTTPStatus
from typing import Any
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.document_response import DocumentResponse
from ...models.http_validation_error import HTTPValidationError
from ...types import Response
def _get_kwargs(
agent_id: str,
document_id: str,
) -> dict[str, Any]:
_kwargs: dict[str, Any] = {
"method": "get",
"url": f"/api/v1/agents/{agent_id}/documents/{document_id}",
}
return _kwargs
def _parse_response(
*, client: AuthenticatedClient | Client, response: httpx.Response
) -> DocumentResponse | HTTPValidationError | None:
if response.status_code == 200:
response_200 = DocumentResponse.from_dict(response.json())
return response_200
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: AuthenticatedClient | Client, response: httpx.Response
) -> Response[DocumentResponse | HTTPValidationError]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
agent_id: str,
document_id: str,
*,
client: AuthenticatedClient | Client,
) -> Response[DocumentResponse | HTTPValidationError]:
"""Get document details
Get a specific document including its original text
Args:
agent_id (str):
document_id (str):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[DocumentResponse | HTTPValidationError]
"""
kwargs = _get_kwargs(
agent_id=agent_id,
document_id=document_id,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
agent_id: str,
document_id: str,
*,
client: AuthenticatedClient | Client,
) -> DocumentResponse | HTTPValidationError | None:
"""Get document details
Get a specific document including its original text
Args:
agent_id (str):
document_id (str):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
DocumentResponse | HTTPValidationError
"""
return sync_detailed(
agent_id=agent_id,
document_id=document_id,
client=client,
).parsed
async def asyncio_detailed(
agent_id: str,
document_id: str,
*,
client: AuthenticatedClient | Client,
) -> Response[DocumentResponse | HTTPValidationError]:
"""Get document details
Get a specific document including its original text
Args:
agent_id (str):
document_id (str):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[DocumentResponse | HTTPValidationError]
"""
kwargs = _get_kwargs(
agent_id=agent_id,
document_id=document_id,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
agent_id: str,
document_id: str,
*,
client: AuthenticatedClient | Client,
) -> DocumentResponse | HTTPValidationError | None:
"""Get document details
Get a specific document including its original text
Args:
agent_id (str):
document_id (str):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
DocumentResponse | HTTPValidationError
"""
return (
await asyncio_detailed(
agent_id=agent_id,
document_id=document_id,
client=client,
)
).parsed

View file

@ -1,225 +0,0 @@
from http import HTTPStatus
from typing import Any
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.http_validation_error import HTTPValidationError
from ...models.list_documents_response import ListDocumentsResponse
from ...types import UNSET, Response, Unset
def _get_kwargs(
agent_id: str,
*,
q: None | str | Unset = UNSET,
limit: int | Unset = 100,
offset: int | Unset = 0,
) -> dict[str, Any]:
params: dict[str, Any] = {}
json_q: None | str | Unset
if isinstance(q, Unset):
json_q = UNSET
else:
json_q = q
params["q"] = json_q
params["limit"] = limit
params["offset"] = offset
params = {k: v for k, v in params.items() if v is not UNSET and v is not None}
_kwargs: dict[str, Any] = {
"method": "get",
"url": f"/api/v1/agents/{agent_id}/documents",
"params": params,
}
return _kwargs
def _parse_response(
*, client: AuthenticatedClient | Client, response: httpx.Response
) -> HTTPValidationError | ListDocumentsResponse | None:
if response.status_code == 200:
response_200 = ListDocumentsResponse.from_dict(response.json())
return response_200
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: AuthenticatedClient | Client, response: httpx.Response
) -> Response[HTTPValidationError | ListDocumentsResponse]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
agent_id: str,
*,
client: AuthenticatedClient | Client,
q: None | str | Unset = UNSET,
limit: int | Unset = 100,
offset: int | Unset = 0,
) -> Response[HTTPValidationError | ListDocumentsResponse]:
"""List documents
List documents with pagination and optional search. Documents are the source content from which
memory units are extracted.
Args:
agent_id (str):
q (None | str | Unset):
limit (int | Unset): Default: 100.
offset (int | Unset): Default: 0.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[HTTPValidationError | ListDocumentsResponse]
"""
kwargs = _get_kwargs(
agent_id=agent_id,
q=q,
limit=limit,
offset=offset,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
agent_id: str,
*,
client: AuthenticatedClient | Client,
q: None | str | Unset = UNSET,
limit: int | Unset = 100,
offset: int | Unset = 0,
) -> HTTPValidationError | ListDocumentsResponse | None:
"""List documents
List documents with pagination and optional search. Documents are the source content from which
memory units are extracted.
Args:
agent_id (str):
q (None | str | Unset):
limit (int | Unset): Default: 100.
offset (int | Unset): Default: 0.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
HTTPValidationError | ListDocumentsResponse
"""
return sync_detailed(
agent_id=agent_id,
client=client,
q=q,
limit=limit,
offset=offset,
).parsed
async def asyncio_detailed(
agent_id: str,
*,
client: AuthenticatedClient | Client,
q: None | str | Unset = UNSET,
limit: int | Unset = 100,
offset: int | Unset = 0,
) -> Response[HTTPValidationError | ListDocumentsResponse]:
"""List documents
List documents with pagination and optional search. Documents are the source content from which
memory units are extracted.
Args:
agent_id (str):
q (None | str | Unset):
limit (int | Unset): Default: 100.
offset (int | Unset): Default: 0.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[HTTPValidationError | ListDocumentsResponse]
"""
kwargs = _get_kwargs(
agent_id=agent_id,
q=q,
limit=limit,
offset=offset,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
agent_id: str,
*,
client: AuthenticatedClient | Client,
q: None | str | Unset = UNSET,
limit: int | Unset = 100,
offset: int | Unset = 0,
) -> HTTPValidationError | ListDocumentsResponse | None:
"""List documents
List documents with pagination and optional search. Documents are the source content from which
memory units are extracted.
Args:
agent_id (str):
q (None | str | Unset):
limit (int | Unset): Default: 100.
offset (int | Unset): Default: 0.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
HTTPValidationError | ListDocumentsResponse
"""
return (
await asyncio_detailed(
agent_id=agent_id,
client=client,
q=q,
limit=limit,
offset=offset,
)
).parsed

View file

@ -1 +0,0 @@
"""Contains endpoint functions for accessing the API"""

View file

@ -1,263 +0,0 @@
from http import HTTPStatus
from typing import Any
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.batch_put_request import BatchPutRequest
from ...models.batch_put_response import BatchPutResponse
from ...models.http_validation_error import HTTPValidationError
from ...types import Response
def _get_kwargs(
agent_id: str,
*,
body: BatchPutRequest,
) -> dict[str, Any]:
headers: dict[str, Any] = {}
_kwargs: dict[str, Any] = {
"method": "post",
"url": f"/api/v1/agents/{agent_id}/memories",
}
_kwargs["json"] = body.to_dict()
headers["Content-Type"] = "application/json"
_kwargs["headers"] = headers
return _kwargs
def _parse_response(
*, client: AuthenticatedClient | Client, response: httpx.Response
) -> BatchPutResponse | HTTPValidationError | None:
if response.status_code == 200:
response_200 = BatchPutResponse.from_dict(response.json())
return response_200
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: AuthenticatedClient | Client, response: httpx.Response
) -> Response[BatchPutResponse | HTTPValidationError]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
agent_id: str,
*,
client: AuthenticatedClient | Client,
body: BatchPutRequest,
) -> Response[BatchPutResponse | HTTPValidationError]:
"""Store multiple memories
Store multiple memory items in batch with automatic fact extraction.
Features:
- Efficient batch processing
- Automatic fact extraction from natural language
- Entity recognition and linking
- Document tracking with automatic upsert (when document_id is provided)
- Temporal and semantic linking
The system automatically:
1. Extracts semantic facts from the content
2. Generates embeddings
3. Deduplicates similar facts
4. Creates temporal, semantic, and entity links
5. Tracks document metadata
Note: If document_id is provided and already exists, the old document and its memory units will
be deleted before creating new ones (upsert behavior).
Args:
agent_id (str):
body (BatchPutRequest): Request model for batch put endpoint. Example: {'document_id':
'conversation_123', 'items': [{'content': 'Alice works at Google', 'context': 'work'},
{'content': 'Bob went hiking yesterday', 'event_date': '2024-01-15T10:00:00Z'}]}.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[BatchPutResponse | HTTPValidationError]
"""
kwargs = _get_kwargs(
agent_id=agent_id,
body=body,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
agent_id: str,
*,
client: AuthenticatedClient | Client,
body: BatchPutRequest,
) -> BatchPutResponse | HTTPValidationError | None:
"""Store multiple memories
Store multiple memory items in batch with automatic fact extraction.
Features:
- Efficient batch processing
- Automatic fact extraction from natural language
- Entity recognition and linking
- Document tracking with automatic upsert (when document_id is provided)
- Temporal and semantic linking
The system automatically:
1. Extracts semantic facts from the content
2. Generates embeddings
3. Deduplicates similar facts
4. Creates temporal, semantic, and entity links
5. Tracks document metadata
Note: If document_id is provided and already exists, the old document and its memory units will
be deleted before creating new ones (upsert behavior).
Args:
agent_id (str):
body (BatchPutRequest): Request model for batch put endpoint. Example: {'document_id':
'conversation_123', 'items': [{'content': 'Alice works at Google', 'context': 'work'},
{'content': 'Bob went hiking yesterday', 'event_date': '2024-01-15T10:00:00Z'}]}.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
BatchPutResponse | HTTPValidationError
"""
return sync_detailed(
agent_id=agent_id,
client=client,
body=body,
).parsed
async def asyncio_detailed(
agent_id: str,
*,
client: AuthenticatedClient | Client,
body: BatchPutRequest,
) -> Response[BatchPutResponse | HTTPValidationError]:
"""Store multiple memories
Store multiple memory items in batch with automatic fact extraction.
Features:
- Efficient batch processing
- Automatic fact extraction from natural language
- Entity recognition and linking
- Document tracking with automatic upsert (when document_id is provided)
- Temporal and semantic linking
The system automatically:
1. Extracts semantic facts from the content
2. Generates embeddings
3. Deduplicates similar facts
4. Creates temporal, semantic, and entity links
5. Tracks document metadata
Note: If document_id is provided and already exists, the old document and its memory units will
be deleted before creating new ones (upsert behavior).
Args:
agent_id (str):
body (BatchPutRequest): Request model for batch put endpoint. Example: {'document_id':
'conversation_123', 'items': [{'content': 'Alice works at Google', 'context': 'work'},
{'content': 'Bob went hiking yesterday', 'event_date': '2024-01-15T10:00:00Z'}]}.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[BatchPutResponse | HTTPValidationError]
"""
kwargs = _get_kwargs(
agent_id=agent_id,
body=body,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
agent_id: str,
*,
client: AuthenticatedClient | Client,
body: BatchPutRequest,
) -> BatchPutResponse | HTTPValidationError | None:
"""Store multiple memories
Store multiple memory items in batch with automatic fact extraction.
Features:
- Efficient batch processing
- Automatic fact extraction from natural language
- Entity recognition and linking
- Document tracking with automatic upsert (when document_id is provided)
- Temporal and semantic linking
The system automatically:
1. Extracts semantic facts from the content
2. Generates embeddings
3. Deduplicates similar facts
4. Creates temporal, semantic, and entity links
5. Tracks document metadata
Note: If document_id is provided and already exists, the old document and its memory units will
be deleted before creating new ones (upsert behavior).
Args:
agent_id (str):
body (BatchPutRequest): Request model for batch put endpoint. Example: {'document_id':
'conversation_123', 'items': [{'content': 'Alice works at Google', 'context': 'work'},
{'content': 'Bob went hiking yesterday', 'event_date': '2024-01-15T10:00:00Z'}]}.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
BatchPutResponse | HTTPValidationError
"""
return (
await asyncio_detailed(
agent_id=agent_id,
client=client,
body=body,
)
).parsed

View file

@ -1,275 +0,0 @@
from http import HTTPStatus
from typing import Any
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.batch_put_async_response import BatchPutAsyncResponse
from ...models.batch_put_request import BatchPutRequest
from ...models.http_validation_error import HTTPValidationError
from ...types import Response
def _get_kwargs(
agent_id: str,
*,
body: BatchPutRequest,
) -> dict[str, Any]:
headers: dict[str, Any] = {}
_kwargs: dict[str, Any] = {
"method": "post",
"url": f"/api/v1/agents/{agent_id}/memories/async",
}
_kwargs["json"] = body.to_dict()
headers["Content-Type"] = "application/json"
_kwargs["headers"] = headers
return _kwargs
def _parse_response(
*, client: AuthenticatedClient | Client, response: httpx.Response
) -> BatchPutAsyncResponse | HTTPValidationError | None:
if response.status_code == 200:
response_200 = BatchPutAsyncResponse.from_dict(response.json())
return response_200
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: AuthenticatedClient | Client, response: httpx.Response
) -> Response[BatchPutAsyncResponse | HTTPValidationError]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
agent_id: str,
*,
client: AuthenticatedClient | Client,
body: BatchPutRequest,
) -> Response[BatchPutAsyncResponse | HTTPValidationError]:
"""Store multiple memories asynchronously
Store multiple memory items in batch asynchronously using the task backend.
This endpoint returns immediately after queuing the task, without waiting for completion.
The actual processing happens in the background.
Features:
- Immediate response (non-blocking)
- Background processing via task queue
- Efficient batch processing
- Automatic fact extraction from natural language
- Entity recognition and linking
- Document tracking with automatic upsert (when document_id is provided)
- Temporal and semantic linking
The system automatically:
1. Queues the batch put task
2. Returns immediately with success=True, queued=True
3. Processes in background: extracts facts, generates embeddings, creates links
Note: If document_id is provided and already exists, the old document and its memory units will
be deleted before creating new ones (upsert behavior).
Args:
agent_id (str):
body (BatchPutRequest): Request model for batch put endpoint. Example: {'document_id':
'conversation_123', 'items': [{'content': 'Alice works at Google', 'context': 'work'},
{'content': 'Bob went hiking yesterday', 'event_date': '2024-01-15T10:00:00Z'}]}.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[BatchPutAsyncResponse | HTTPValidationError]
"""
kwargs = _get_kwargs(
agent_id=agent_id,
body=body,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
agent_id: str,
*,
client: AuthenticatedClient | Client,
body: BatchPutRequest,
) -> BatchPutAsyncResponse | HTTPValidationError | None:
"""Store multiple memories asynchronously
Store multiple memory items in batch asynchronously using the task backend.
This endpoint returns immediately after queuing the task, without waiting for completion.
The actual processing happens in the background.
Features:
- Immediate response (non-blocking)
- Background processing via task queue
- Efficient batch processing
- Automatic fact extraction from natural language
- Entity recognition and linking
- Document tracking with automatic upsert (when document_id is provided)
- Temporal and semantic linking
The system automatically:
1. Queues the batch put task
2. Returns immediately with success=True, queued=True
3. Processes in background: extracts facts, generates embeddings, creates links
Note: If document_id is provided and already exists, the old document and its memory units will
be deleted before creating new ones (upsert behavior).
Args:
agent_id (str):
body (BatchPutRequest): Request model for batch put endpoint. Example: {'document_id':
'conversation_123', 'items': [{'content': 'Alice works at Google', 'context': 'work'},
{'content': 'Bob went hiking yesterday', 'event_date': '2024-01-15T10:00:00Z'}]}.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
BatchPutAsyncResponse | HTTPValidationError
"""
return sync_detailed(
agent_id=agent_id,
client=client,
body=body,
).parsed
async def asyncio_detailed(
agent_id: str,
*,
client: AuthenticatedClient | Client,
body: BatchPutRequest,
) -> Response[BatchPutAsyncResponse | HTTPValidationError]:
"""Store multiple memories asynchronously
Store multiple memory items in batch asynchronously using the task backend.
This endpoint returns immediately after queuing the task, without waiting for completion.
The actual processing happens in the background.
Features:
- Immediate response (non-blocking)
- Background processing via task queue
- Efficient batch processing
- Automatic fact extraction from natural language
- Entity recognition and linking
- Document tracking with automatic upsert (when document_id is provided)
- Temporal and semantic linking
The system automatically:
1. Queues the batch put task
2. Returns immediately with success=True, queued=True
3. Processes in background: extracts facts, generates embeddings, creates links
Note: If document_id is provided and already exists, the old document and its memory units will
be deleted before creating new ones (upsert behavior).
Args:
agent_id (str):
body (BatchPutRequest): Request model for batch put endpoint. Example: {'document_id':
'conversation_123', 'items': [{'content': 'Alice works at Google', 'context': 'work'},
{'content': 'Bob went hiking yesterday', 'event_date': '2024-01-15T10:00:00Z'}]}.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[BatchPutAsyncResponse | HTTPValidationError]
"""
kwargs = _get_kwargs(
agent_id=agent_id,
body=body,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
agent_id: str,
*,
client: AuthenticatedClient | Client,
body: BatchPutRequest,
) -> BatchPutAsyncResponse | HTTPValidationError | None:
"""Store multiple memories asynchronously
Store multiple memory items in batch asynchronously using the task backend.
This endpoint returns immediately after queuing the task, without waiting for completion.
The actual processing happens in the background.
Features:
- Immediate response (non-blocking)
- Background processing via task queue
- Efficient batch processing
- Automatic fact extraction from natural language
- Entity recognition and linking
- Document tracking with automatic upsert (when document_id is provided)
- Temporal and semantic linking
The system automatically:
1. Queues the batch put task
2. Returns immediately with success=True, queued=True
3. Processes in background: extracts facts, generates embeddings, creates links
Note: If document_id is provided and already exists, the old document and its memory units will
be deleted before creating new ones (upsert behavior).
Args:
agent_id (str):
body (BatchPutRequest): Request model for batch put endpoint. Example: {'document_id':
'conversation_123', 'items': [{'content': 'Alice works at Google', 'context': 'work'},
{'content': 'Bob went hiking yesterday', 'event_date': '2024-01-15T10:00:00Z'}]}.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
BatchPutAsyncResponse | HTTPValidationError
"""
return (
await asyncio_detailed(
agent_id=agent_id,
client=client,
body=body,
)
).parsed

View file

@ -1,176 +0,0 @@
from http import HTTPStatus
from typing import Any
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.http_validation_error import HTTPValidationError
from ...types import Response
def _get_kwargs(
agent_id: str,
operation_id: str,
) -> dict[str, Any]:
_kwargs: dict[str, Any] = {
"method": "delete",
"url": f"/api/v1/agents/{agent_id}/operations/{operation_id}",
}
return _kwargs
def _parse_response(
*, client: AuthenticatedClient | Client, response: httpx.Response
) -> Any | HTTPValidationError | None:
if response.status_code == 200:
response_200 = response.json()
return response_200
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: AuthenticatedClient | Client, response: httpx.Response
) -> Response[Any | HTTPValidationError]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
agent_id: str,
operation_id: str,
*,
client: AuthenticatedClient | Client,
) -> Response[Any | HTTPValidationError]:
"""Cancel a pending async operation
Cancel a pending async operation by removing it from the queue
Args:
agent_id (str):
operation_id (str):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Any | HTTPValidationError]
"""
kwargs = _get_kwargs(
agent_id=agent_id,
operation_id=operation_id,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
agent_id: str,
operation_id: str,
*,
client: AuthenticatedClient | Client,
) -> Any | HTTPValidationError | None:
"""Cancel a pending async operation
Cancel a pending async operation by removing it from the queue
Args:
agent_id (str):
operation_id (str):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Any | HTTPValidationError
"""
return sync_detailed(
agent_id=agent_id,
operation_id=operation_id,
client=client,
).parsed
async def asyncio_detailed(
agent_id: str,
operation_id: str,
*,
client: AuthenticatedClient | Client,
) -> Response[Any | HTTPValidationError]:
"""Cancel a pending async operation
Cancel a pending async operation by removing it from the queue
Args:
agent_id (str):
operation_id (str):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Any | HTTPValidationError]
"""
kwargs = _get_kwargs(
agent_id=agent_id,
operation_id=operation_id,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
agent_id: str,
operation_id: str,
*,
client: AuthenticatedClient | Client,
) -> Any | HTTPValidationError | None:
"""Cancel a pending async operation
Cancel a pending async operation by removing it from the queue
Args:
agent_id (str):
operation_id (str):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Any | HTTPValidationError
"""
return (
await asyncio_detailed(
agent_id=agent_id,
operation_id=operation_id,
client=client,
)
).parsed

View file

@ -1,176 +0,0 @@
from http import HTTPStatus
from typing import Any
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.http_validation_error import HTTPValidationError
from ...types import Response
def _get_kwargs(
agent_id: str,
unit_id: str,
) -> dict[str, Any]:
_kwargs: dict[str, Any] = {
"method": "delete",
"url": f"/api/v1/agents/{agent_id}/memories/{unit_id}",
}
return _kwargs
def _parse_response(
*, client: AuthenticatedClient | Client, response: httpx.Response
) -> Any | HTTPValidationError | None:
if response.status_code == 200:
response_200 = response.json()
return response_200
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: AuthenticatedClient | Client, response: httpx.Response
) -> Response[Any | HTTPValidationError]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
agent_id: str,
unit_id: str,
*,
client: AuthenticatedClient | Client,
) -> Response[Any | HTTPValidationError]:
"""Delete a memory unit
Delete a single memory unit and all its associated links (temporal, semantic, and entity links)
Args:
agent_id (str):
unit_id (str):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Any | HTTPValidationError]
"""
kwargs = _get_kwargs(
agent_id=agent_id,
unit_id=unit_id,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
agent_id: str,
unit_id: str,
*,
client: AuthenticatedClient | Client,
) -> Any | HTTPValidationError | None:
"""Delete a memory unit
Delete a single memory unit and all its associated links (temporal, semantic, and entity links)
Args:
agent_id (str):
unit_id (str):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Any | HTTPValidationError
"""
return sync_detailed(
agent_id=agent_id,
unit_id=unit_id,
client=client,
).parsed
async def asyncio_detailed(
agent_id: str,
unit_id: str,
*,
client: AuthenticatedClient | Client,
) -> Response[Any | HTTPValidationError]:
"""Delete a memory unit
Delete a single memory unit and all its associated links (temporal, semantic, and entity links)
Args:
agent_id (str):
unit_id (str):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Any | HTTPValidationError]
"""
kwargs = _get_kwargs(
agent_id=agent_id,
unit_id=unit_id,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
agent_id: str,
unit_id: str,
*,
client: AuthenticatedClient | Client,
) -> Any | HTTPValidationError | None:
"""Delete a memory unit
Delete a single memory unit and all its associated links (temporal, semantic, and entity links)
Args:
agent_id (str):
unit_id (str):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Any | HTTPValidationError
"""
return (
await asyncio_detailed(
agent_id=agent_id,
unit_id=unit_id,
client=client,
)
).parsed

View file

@ -1,241 +0,0 @@
from http import HTTPStatus
from typing import Any
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.http_validation_error import HTTPValidationError
from ...models.list_memory_units_response import ListMemoryUnitsResponse
from ...types import UNSET, Response, Unset
def _get_kwargs(
agent_id: str,
*,
fact_type: None | str | Unset = UNSET,
q: None | str | Unset = UNSET,
limit: int | Unset = 100,
offset: int | Unset = 0,
) -> dict[str, Any]:
params: dict[str, Any] = {}
json_fact_type: None | str | Unset
if isinstance(fact_type, Unset):
json_fact_type = UNSET
else:
json_fact_type = fact_type
params["fact_type"] = json_fact_type
json_q: None | str | Unset
if isinstance(q, Unset):
json_q = UNSET
else:
json_q = q
params["q"] = json_q
params["limit"] = limit
params["offset"] = offset
params = {k: v for k, v in params.items() if v is not UNSET and v is not None}
_kwargs: dict[str, Any] = {
"method": "get",
"url": f"/api/v1/agents/{agent_id}/memories/list",
"params": params,
}
return _kwargs
def _parse_response(
*, client: AuthenticatedClient | Client, response: httpx.Response
) -> HTTPValidationError | ListMemoryUnitsResponse | None:
if response.status_code == 200:
response_200 = ListMemoryUnitsResponse.from_dict(response.json())
return response_200
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: AuthenticatedClient | Client, response: httpx.Response
) -> Response[HTTPValidationError | ListMemoryUnitsResponse]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
agent_id: str,
*,
client: AuthenticatedClient | Client,
fact_type: None | str | Unset = UNSET,
q: None | str | Unset = UNSET,
limit: int | Unset = 100,
offset: int | Unset = 0,
) -> Response[HTTPValidationError | ListMemoryUnitsResponse]:
"""List memory units
List memory units with pagination and optional full-text search. Supports filtering by fact_type.
Args:
agent_id (str):
fact_type (None | str | Unset):
q (None | str | Unset):
limit (int | Unset): Default: 100.
offset (int | Unset): Default: 0.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[HTTPValidationError | ListMemoryUnitsResponse]
"""
kwargs = _get_kwargs(
agent_id=agent_id,
fact_type=fact_type,
q=q,
limit=limit,
offset=offset,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
agent_id: str,
*,
client: AuthenticatedClient | Client,
fact_type: None | str | Unset = UNSET,
q: None | str | Unset = UNSET,
limit: int | Unset = 100,
offset: int | Unset = 0,
) -> HTTPValidationError | ListMemoryUnitsResponse | None:
"""List memory units
List memory units with pagination and optional full-text search. Supports filtering by fact_type.
Args:
agent_id (str):
fact_type (None | str | Unset):
q (None | str | Unset):
limit (int | Unset): Default: 100.
offset (int | Unset): Default: 0.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
HTTPValidationError | ListMemoryUnitsResponse
"""
return sync_detailed(
agent_id=agent_id,
client=client,
fact_type=fact_type,
q=q,
limit=limit,
offset=offset,
).parsed
async def asyncio_detailed(
agent_id: str,
*,
client: AuthenticatedClient | Client,
fact_type: None | str | Unset = UNSET,
q: None | str | Unset = UNSET,
limit: int | Unset = 100,
offset: int | Unset = 0,
) -> Response[HTTPValidationError | ListMemoryUnitsResponse]:
"""List memory units
List memory units with pagination and optional full-text search. Supports filtering by fact_type.
Args:
agent_id (str):
fact_type (None | str | Unset):
q (None | str | Unset):
limit (int | Unset): Default: 100.
offset (int | Unset): Default: 0.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[HTTPValidationError | ListMemoryUnitsResponse]
"""
kwargs = _get_kwargs(
agent_id=agent_id,
fact_type=fact_type,
q=q,
limit=limit,
offset=offset,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
agent_id: str,
*,
client: AuthenticatedClient | Client,
fact_type: None | str | Unset = UNSET,
q: None | str | Unset = UNSET,
limit: int | Unset = 100,
offset: int | Unset = 0,
) -> HTTPValidationError | ListMemoryUnitsResponse | None:
"""List memory units
List memory units with pagination and optional full-text search. Supports filtering by fact_type.
Args:
agent_id (str):
fact_type (None | str | Unset):
q (None | str | Unset):
limit (int | Unset): Default: 100.
offset (int | Unset): Default: 0.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
HTTPValidationError | ListMemoryUnitsResponse
"""
return (
await asyncio_detailed(
agent_id=agent_id,
client=client,
fact_type=fact_type,
q=q,
limit=limit,
offset=offset,
)
).parsed

View file

@ -1,167 +0,0 @@
from http import HTTPStatus
from typing import Any
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.http_validation_error import HTTPValidationError
from ...types import Response
def _get_kwargs(
agent_id: str,
) -> dict[str, Any]:
_kwargs: dict[str, Any] = {
"method": "get",
"url": f"/api/v1/agents/{agent_id}/operations",
}
return _kwargs
def _parse_response(
*, client: AuthenticatedClient | Client, response: httpx.Response
) -> Any | HTTPValidationError | None:
if response.status_code == 200:
response_200 = response.json()
return response_200
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: AuthenticatedClient | Client, response: httpx.Response
) -> Response[Any | HTTPValidationError]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
agent_id: str,
*,
client: AuthenticatedClient | Client,
) -> Response[Any | HTTPValidationError]:
"""List async operations
Get a list of all async operations (pending and failed) for a specific agent, including error
messages for failed operations
Args:
agent_id (str):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Any | HTTPValidationError]
"""
kwargs = _get_kwargs(
agent_id=agent_id,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
agent_id: str,
*,
client: AuthenticatedClient | Client,
) -> Any | HTTPValidationError | None:
"""List async operations
Get a list of all async operations (pending and failed) for a specific agent, including error
messages for failed operations
Args:
agent_id (str):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Any | HTTPValidationError
"""
return sync_detailed(
agent_id=agent_id,
client=client,
).parsed
async def asyncio_detailed(
agent_id: str,
*,
client: AuthenticatedClient | Client,
) -> Response[Any | HTTPValidationError]:
"""List async operations
Get a list of all async operations (pending and failed) for a specific agent, including error
messages for failed operations
Args:
agent_id (str):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Any | HTTPValidationError]
"""
kwargs = _get_kwargs(
agent_id=agent_id,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
agent_id: str,
*,
client: AuthenticatedClient | Client,
) -> Any | HTTPValidationError | None:
"""List async operations
Get a list of all async operations (pending and failed) for a specific agent, including error
messages for failed operations
Args:
agent_id (str):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Any | HTTPValidationError
"""
return (
await asyncio_detailed(
agent_id=agent_id,
client=client,
)
).parsed

View file

@ -1,219 +0,0 @@
from http import HTTPStatus
from typing import Any
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.http_validation_error import HTTPValidationError
from ...models.search_request import SearchRequest
from ...models.search_response import SearchResponse
from ...types import Response
def _get_kwargs(
agent_id: str,
*,
body: SearchRequest,
) -> dict[str, Any]:
headers: dict[str, Any] = {}
_kwargs: dict[str, Any] = {
"method": "post",
"url": f"/api/v1/agents/{agent_id}/memories/search",
}
_kwargs["json"] = body.to_dict()
headers["Content-Type"] = "application/json"
_kwargs["headers"] = headers
return _kwargs
def _parse_response(
*, client: AuthenticatedClient | Client, response: httpx.Response
) -> HTTPValidationError | SearchResponse | None:
if response.status_code == 200:
response_200 = SearchResponse.from_dict(response.json())
return response_200
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: AuthenticatedClient | Client, response: httpx.Response
) -> Response[HTTPValidationError | SearchResponse]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
agent_id: str,
*,
client: AuthenticatedClient | Client,
body: SearchRequest,
) -> Response[HTTPValidationError | SearchResponse]:
"""Search memory
Search memory using semantic similarity and spreading activation.
The fact_type parameter is optional and must be one of:
- 'world': General knowledge about people, places, events, and things that happen
- 'agent': Memories about what the AI agent did, actions taken, and tasks performed
- 'opinion': The agent's formed beliefs, perspectives, and viewpoints
Args:
agent_id (str):
body (SearchRequest): Request model for search endpoint. Example: {'fact_type': ['world',
'agent'], 'max_tokens': 4096, 'query': 'What did Alice say about machine learning?',
'question_date': '2023-05-30T23:40:00', 'reranker': 'heuristic', 'thinking_budget': 100,
'trace': True}.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[HTTPValidationError | SearchResponse]
"""
kwargs = _get_kwargs(
agent_id=agent_id,
body=body,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
agent_id: str,
*,
client: AuthenticatedClient | Client,
body: SearchRequest,
) -> HTTPValidationError | SearchResponse | None:
"""Search memory
Search memory using semantic similarity and spreading activation.
The fact_type parameter is optional and must be one of:
- 'world': General knowledge about people, places, events, and things that happen
- 'agent': Memories about what the AI agent did, actions taken, and tasks performed
- 'opinion': The agent's formed beliefs, perspectives, and viewpoints
Args:
agent_id (str):
body (SearchRequest): Request model for search endpoint. Example: {'fact_type': ['world',
'agent'], 'max_tokens': 4096, 'query': 'What did Alice say about machine learning?',
'question_date': '2023-05-30T23:40:00', 'reranker': 'heuristic', 'thinking_budget': 100,
'trace': True}.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
HTTPValidationError | SearchResponse
"""
return sync_detailed(
agent_id=agent_id,
client=client,
body=body,
).parsed
async def asyncio_detailed(
agent_id: str,
*,
client: AuthenticatedClient | Client,
body: SearchRequest,
) -> Response[HTTPValidationError | SearchResponse]:
"""Search memory
Search memory using semantic similarity and spreading activation.
The fact_type parameter is optional and must be one of:
- 'world': General knowledge about people, places, events, and things that happen
- 'agent': Memories about what the AI agent did, actions taken, and tasks performed
- 'opinion': The agent's formed beliefs, perspectives, and viewpoints
Args:
agent_id (str):
body (SearchRequest): Request model for search endpoint. Example: {'fact_type': ['world',
'agent'], 'max_tokens': 4096, 'query': 'What did Alice say about machine learning?',
'question_date': '2023-05-30T23:40:00', 'reranker': 'heuristic', 'thinking_budget': 100,
'trace': True}.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[HTTPValidationError | SearchResponse]
"""
kwargs = _get_kwargs(
agent_id=agent_id,
body=body,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
agent_id: str,
*,
client: AuthenticatedClient | Client,
body: SearchRequest,
) -> HTTPValidationError | SearchResponse | None:
"""Search memory
Search memory using semantic similarity and spreading activation.
The fact_type parameter is optional and must be one of:
- 'world': General knowledge about people, places, events, and things that happen
- 'agent': Memories about what the AI agent did, actions taken, and tasks performed
- 'opinion': The agent's formed beliefs, perspectives, and viewpoints
Args:
agent_id (str):
body (SearchRequest): Request model for search endpoint. Example: {'fact_type': ['world',
'agent'], 'max_tokens': 4096, 'query': 'What did Alice say about machine learning?',
'question_date': '2023-05-30T23:40:00', 'reranker': 'heuristic', 'thinking_budget': 100,
'trace': True}.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
HTTPValidationError | SearchResponse
"""
return (
await asyncio_detailed(
agent_id=agent_id,
client=client,
body=body,
)
).parsed

View file

@ -1 +0,0 @@
"""Contains endpoint functions for accessing the API"""

View file

@ -1,227 +0,0 @@
from http import HTTPStatus
from typing import Any
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.http_validation_error import HTTPValidationError
from ...models.think_request import ThinkRequest
from ...models.think_response import ThinkResponse
from ...types import Response
def _get_kwargs(
agent_id: str,
*,
body: ThinkRequest,
) -> dict[str, Any]:
headers: dict[str, Any] = {}
_kwargs: dict[str, Any] = {
"method": "post",
"url": f"/api/v1/agents/{agent_id}/think",
}
_kwargs["json"] = body.to_dict()
headers["Content-Type"] = "application/json"
_kwargs["headers"] = headers
return _kwargs
def _parse_response(
*, client: AuthenticatedClient | Client, response: httpx.Response
) -> HTTPValidationError | ThinkResponse | None:
if response.status_code == 200:
response_200 = ThinkResponse.from_dict(response.json())
return response_200
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: AuthenticatedClient | Client, response: httpx.Response
) -> Response[HTTPValidationError | ThinkResponse]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
agent_id: str,
*,
client: AuthenticatedClient | Client,
body: ThinkRequest,
) -> Response[HTTPValidationError | ThinkResponse]:
"""Think and generate answer
Think and formulate an answer using agent identity, world facts, and opinions.
This endpoint:
1. Retrieves agent facts (agent's identity)
2. Retrieves world facts relevant to the query
3. Retrieves existing opinions (agent's perspectives)
4. Uses LLM to formulate a contextual answer
5. Extracts and stores any new opinions formed
6. Returns plain text answer, the facts used, and new opinions
Args:
agent_id (str):
body (ThinkRequest): Request model for think endpoint. Example: {'context': 'This is for a
research paper on AI ethics', 'query': 'What do you think about artificial intelligence?',
'thinking_budget': 50}.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[HTTPValidationError | ThinkResponse]
"""
kwargs = _get_kwargs(
agent_id=agent_id,
body=body,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
agent_id: str,
*,
client: AuthenticatedClient | Client,
body: ThinkRequest,
) -> HTTPValidationError | ThinkResponse | None:
"""Think and generate answer
Think and formulate an answer using agent identity, world facts, and opinions.
This endpoint:
1. Retrieves agent facts (agent's identity)
2. Retrieves world facts relevant to the query
3. Retrieves existing opinions (agent's perspectives)
4. Uses LLM to formulate a contextual answer
5. Extracts and stores any new opinions formed
6. Returns plain text answer, the facts used, and new opinions
Args:
agent_id (str):
body (ThinkRequest): Request model for think endpoint. Example: {'context': 'This is for a
research paper on AI ethics', 'query': 'What do you think about artificial intelligence?',
'thinking_budget': 50}.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
HTTPValidationError | ThinkResponse
"""
return sync_detailed(
agent_id=agent_id,
client=client,
body=body,
).parsed
async def asyncio_detailed(
agent_id: str,
*,
client: AuthenticatedClient | Client,
body: ThinkRequest,
) -> Response[HTTPValidationError | ThinkResponse]:
"""Think and generate answer
Think and formulate an answer using agent identity, world facts, and opinions.
This endpoint:
1. Retrieves agent facts (agent's identity)
2. Retrieves world facts relevant to the query
3. Retrieves existing opinions (agent's perspectives)
4. Uses LLM to formulate a contextual answer
5. Extracts and stores any new opinions formed
6. Returns plain text answer, the facts used, and new opinions
Args:
agent_id (str):
body (ThinkRequest): Request model for think endpoint. Example: {'context': 'This is for a
research paper on AI ethics', 'query': 'What do you think about artificial intelligence?',
'thinking_budget': 50}.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[HTTPValidationError | ThinkResponse]
"""
kwargs = _get_kwargs(
agent_id=agent_id,
body=body,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
agent_id: str,
*,
client: AuthenticatedClient | Client,
body: ThinkRequest,
) -> HTTPValidationError | ThinkResponse | None:
"""Think and generate answer
Think and formulate an answer using agent identity, world facts, and opinions.
This endpoint:
1. Retrieves agent facts (agent's identity)
2. Retrieves world facts relevant to the query
3. Retrieves existing opinions (agent's perspectives)
4. Uses LLM to formulate a contextual answer
5. Extracts and stores any new opinions formed
6. Returns plain text answer, the facts used, and new opinions
Args:
agent_id (str):
body (ThinkRequest): Request model for think endpoint. Example: {'context': 'This is for a
research paper on AI ethics', 'query': 'What do you think about artificial intelligence?',
'thinking_budget': 50}.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
HTTPValidationError | ThinkResponse
"""
return (
await asyncio_detailed(
agent_id=agent_id,
client=client,
body=body,
)
).parsed

View file

@ -1 +0,0 @@
"""Contains endpoint functions for accessing the API"""

View file

@ -1,195 +0,0 @@
from http import HTTPStatus
from typing import Any
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.graph_data_response import GraphDataResponse
from ...models.http_validation_error import HTTPValidationError
from ...types import UNSET, Response, Unset
def _get_kwargs(
agent_id: str,
*,
fact_type: None | str | Unset = UNSET,
) -> dict[str, Any]:
params: dict[str, Any] = {}
json_fact_type: None | str | Unset
if isinstance(fact_type, Unset):
json_fact_type = UNSET
else:
json_fact_type = fact_type
params["fact_type"] = json_fact_type
params = {k: v for k, v in params.items() if v is not UNSET and v is not None}
_kwargs: dict[str, Any] = {
"method": "get",
"url": f"/api/v1/agents/{agent_id}/graph",
"params": params,
}
return _kwargs
def _parse_response(
*, client: AuthenticatedClient | Client, response: httpx.Response
) -> GraphDataResponse | HTTPValidationError | None:
if response.status_code == 200:
response_200 = GraphDataResponse.from_dict(response.json())
return response_200
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: AuthenticatedClient | Client, response: httpx.Response
) -> Response[GraphDataResponse | HTTPValidationError]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
agent_id: str,
*,
client: AuthenticatedClient | Client,
fact_type: None | str | Unset = UNSET,
) -> Response[GraphDataResponse | HTTPValidationError]:
"""Get memory graph data
Retrieve graph data for visualization, optionally filtered by fact_type (world/agent/opinion).
Limited to 1000 most recent items.
Args:
agent_id (str):
fact_type (None | str | Unset):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[GraphDataResponse | HTTPValidationError]
"""
kwargs = _get_kwargs(
agent_id=agent_id,
fact_type=fact_type,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
agent_id: str,
*,
client: AuthenticatedClient | Client,
fact_type: None | str | Unset = UNSET,
) -> GraphDataResponse | HTTPValidationError | None:
"""Get memory graph data
Retrieve graph data for visualization, optionally filtered by fact_type (world/agent/opinion).
Limited to 1000 most recent items.
Args:
agent_id (str):
fact_type (None | str | Unset):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
GraphDataResponse | HTTPValidationError
"""
return sync_detailed(
agent_id=agent_id,
client=client,
fact_type=fact_type,
).parsed
async def asyncio_detailed(
agent_id: str,
*,
client: AuthenticatedClient | Client,
fact_type: None | str | Unset = UNSET,
) -> Response[GraphDataResponse | HTTPValidationError]:
"""Get memory graph data
Retrieve graph data for visualization, optionally filtered by fact_type (world/agent/opinion).
Limited to 1000 most recent items.
Args:
agent_id (str):
fact_type (None | str | Unset):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[GraphDataResponse | HTTPValidationError]
"""
kwargs = _get_kwargs(
agent_id=agent_id,
fact_type=fact_type,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
agent_id: str,
*,
client: AuthenticatedClient | Client,
fact_type: None | str | Unset = UNSET,
) -> GraphDataResponse | HTTPValidationError | None:
"""Get memory graph data
Retrieve graph data for visualization, optionally filtered by fact_type (world/agent/opinion).
Limited to 1000 most recent items.
Args:
agent_id (str):
fact_type (None | str | Unset):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
GraphDataResponse | HTTPValidationError
"""
return (
await asyncio_detailed(
agent_id=agent_id,
client=client,
fact_type=fact_type,
)
).parsed

View file

@ -1,268 +0,0 @@
import ssl
from typing import Any
import httpx
from attrs import define, evolve, field
@define
class Client:
"""A class for keeping track of data related to the API
The following are accepted as keyword arguments and will be used to construct httpx Clients internally:
``base_url``: The base URL for the API, all requests are made to a relative path to this URL
``cookies``: A dictionary of cookies to be sent with every request
``headers``: A dictionary of headers to be sent with every request
``timeout``: The maximum amount of a time a request can take. API functions will raise
httpx.TimeoutException if this is exceeded.
``verify_ssl``: Whether or not to verify the SSL certificate of the API server. This should be True in production,
but can be set to False for testing purposes.
``follow_redirects``: Whether or not to follow redirects. Default value is False.
``httpx_args``: A dictionary of additional arguments to be passed to the ``httpx.Client`` and ``httpx.AsyncClient`` constructor.
Attributes:
raise_on_unexpected_status: Whether or not to raise an errors.UnexpectedStatus if the API returns a
status code that was not documented in the source OpenAPI document. Can also be provided as a keyword
argument to the constructor.
"""
raise_on_unexpected_status: bool = field(default=False, kw_only=True)
_base_url: str = field(alias="base_url")
_cookies: dict[str, str] = field(factory=dict, kw_only=True, alias="cookies")
_headers: dict[str, str] = field(factory=dict, kw_only=True, alias="headers")
_timeout: httpx.Timeout | None = field(default=None, kw_only=True, alias="timeout")
_verify_ssl: str | bool | ssl.SSLContext = field(default=True, kw_only=True, alias="verify_ssl")
_follow_redirects: bool = field(default=False, kw_only=True, alias="follow_redirects")
_httpx_args: dict[str, Any] = field(factory=dict, kw_only=True, alias="httpx_args")
_client: httpx.Client | None = field(default=None, init=False)
_async_client: httpx.AsyncClient | None = field(default=None, init=False)
def with_headers(self, headers: dict[str, str]) -> "Client":
"""Get a new client matching this one with additional headers"""
if self._client is not None:
self._client.headers.update(headers)
if self._async_client is not None:
self._async_client.headers.update(headers)
return evolve(self, headers={**self._headers, **headers})
def with_cookies(self, cookies: dict[str, str]) -> "Client":
"""Get a new client matching this one with additional cookies"""
if self._client is not None:
self._client.cookies.update(cookies)
if self._async_client is not None:
self._async_client.cookies.update(cookies)
return evolve(self, cookies={**self._cookies, **cookies})
def with_timeout(self, timeout: httpx.Timeout) -> "Client":
"""Get a new client matching this one with a new timeout configuration"""
if self._client is not None:
self._client.timeout = timeout
if self._async_client is not None:
self._async_client.timeout = timeout
return evolve(self, timeout=timeout)
def set_httpx_client(self, client: httpx.Client) -> "Client":
"""Manually set the underlying httpx.Client
**NOTE**: This will override any other settings on the client, including cookies, headers, and timeout.
"""
self._client = client
return self
def get_httpx_client(self) -> httpx.Client:
"""Get the underlying httpx.Client, constructing a new one if not previously set"""
if self._client is None:
self._client = httpx.Client(
base_url=self._base_url,
cookies=self._cookies,
headers=self._headers,
timeout=self._timeout,
verify=self._verify_ssl,
follow_redirects=self._follow_redirects,
**self._httpx_args,
)
return self._client
def __enter__(self) -> "Client":
"""Enter a context manager for self.client—you cannot enter twice (see httpx docs)"""
self.get_httpx_client().__enter__()
return self
def __exit__(self, *args: Any, **kwargs: Any) -> None:
"""Exit a context manager for internal httpx.Client (see httpx docs)"""
self.get_httpx_client().__exit__(*args, **kwargs)
def set_async_httpx_client(self, async_client: httpx.AsyncClient) -> "Client":
"""Manually set the underlying httpx.AsyncClient
**NOTE**: This will override any other settings on the client, including cookies, headers, and timeout.
"""
self._async_client = async_client
return self
def get_async_httpx_client(self) -> httpx.AsyncClient:
"""Get the underlying httpx.AsyncClient, constructing a new one if not previously set"""
if self._async_client is None:
self._async_client = httpx.AsyncClient(
base_url=self._base_url,
cookies=self._cookies,
headers=self._headers,
timeout=self._timeout,
verify=self._verify_ssl,
follow_redirects=self._follow_redirects,
**self._httpx_args,
)
return self._async_client
async def __aenter__(self) -> "Client":
"""Enter a context manager for underlying httpx.AsyncClient—you cannot enter twice (see httpx docs)"""
await self.get_async_httpx_client().__aenter__()
return self
async def __aexit__(self, *args: Any, **kwargs: Any) -> None:
"""Exit a context manager for underlying httpx.AsyncClient (see httpx docs)"""
await self.get_async_httpx_client().__aexit__(*args, **kwargs)
@define
class AuthenticatedClient:
"""A Client which has been authenticated for use on secured endpoints
The following are accepted as keyword arguments and will be used to construct httpx Clients internally:
``base_url``: The base URL for the API, all requests are made to a relative path to this URL
``cookies``: A dictionary of cookies to be sent with every request
``headers``: A dictionary of headers to be sent with every request
``timeout``: The maximum amount of a time a request can take. API functions will raise
httpx.TimeoutException if this is exceeded.
``verify_ssl``: Whether or not to verify the SSL certificate of the API server. This should be True in production,
but can be set to False for testing purposes.
``follow_redirects``: Whether or not to follow redirects. Default value is False.
``httpx_args``: A dictionary of additional arguments to be passed to the ``httpx.Client`` and ``httpx.AsyncClient`` constructor.
Attributes:
raise_on_unexpected_status: Whether or not to raise an errors.UnexpectedStatus if the API returns a
status code that was not documented in the source OpenAPI document. Can also be provided as a keyword
argument to the constructor.
token: The token to use for authentication
prefix: The prefix to use for the Authorization header
auth_header_name: The name of the Authorization header
"""
raise_on_unexpected_status: bool = field(default=False, kw_only=True)
_base_url: str = field(alias="base_url")
_cookies: dict[str, str] = field(factory=dict, kw_only=True, alias="cookies")
_headers: dict[str, str] = field(factory=dict, kw_only=True, alias="headers")
_timeout: httpx.Timeout | None = field(default=None, kw_only=True, alias="timeout")
_verify_ssl: str | bool | ssl.SSLContext = field(default=True, kw_only=True, alias="verify_ssl")
_follow_redirects: bool = field(default=False, kw_only=True, alias="follow_redirects")
_httpx_args: dict[str, Any] = field(factory=dict, kw_only=True, alias="httpx_args")
_client: httpx.Client | None = field(default=None, init=False)
_async_client: httpx.AsyncClient | None = field(default=None, init=False)
token: str
prefix: str = "Bearer"
auth_header_name: str = "Authorization"
def with_headers(self, headers: dict[str, str]) -> "AuthenticatedClient":
"""Get a new client matching this one with additional headers"""
if self._client is not None:
self._client.headers.update(headers)
if self._async_client is not None:
self._async_client.headers.update(headers)
return evolve(self, headers={**self._headers, **headers})
def with_cookies(self, cookies: dict[str, str]) -> "AuthenticatedClient":
"""Get a new client matching this one with additional cookies"""
if self._client is not None:
self._client.cookies.update(cookies)
if self._async_client is not None:
self._async_client.cookies.update(cookies)
return evolve(self, cookies={**self._cookies, **cookies})
def with_timeout(self, timeout: httpx.Timeout) -> "AuthenticatedClient":
"""Get a new client matching this one with a new timeout configuration"""
if self._client is not None:
self._client.timeout = timeout
if self._async_client is not None:
self._async_client.timeout = timeout
return evolve(self, timeout=timeout)
def set_httpx_client(self, client: httpx.Client) -> "AuthenticatedClient":
"""Manually set the underlying httpx.Client
**NOTE**: This will override any other settings on the client, including cookies, headers, and timeout.
"""
self._client = client
return self
def get_httpx_client(self) -> httpx.Client:
"""Get the underlying httpx.Client, constructing a new one if not previously set"""
if self._client is None:
self._headers[self.auth_header_name] = f"{self.prefix} {self.token}" if self.prefix else self.token
self._client = httpx.Client(
base_url=self._base_url,
cookies=self._cookies,
headers=self._headers,
timeout=self._timeout,
verify=self._verify_ssl,
follow_redirects=self._follow_redirects,
**self._httpx_args,
)
return self._client
def __enter__(self) -> "AuthenticatedClient":
"""Enter a context manager for self.client—you cannot enter twice (see httpx docs)"""
self.get_httpx_client().__enter__()
return self
def __exit__(self, *args: Any, **kwargs: Any) -> None:
"""Exit a context manager for internal httpx.Client (see httpx docs)"""
self.get_httpx_client().__exit__(*args, **kwargs)
def set_async_httpx_client(self, async_client: httpx.AsyncClient) -> "AuthenticatedClient":
"""Manually set the underlying httpx.AsyncClient
**NOTE**: This will override any other settings on the client, including cookies, headers, and timeout.
"""
self._async_client = async_client
return self
def get_async_httpx_client(self) -> httpx.AsyncClient:
"""Get the underlying httpx.AsyncClient, constructing a new one if not previously set"""
if self._async_client is None:
self._headers[self.auth_header_name] = f"{self.prefix} {self.token}" if self.prefix else self.token
self._async_client = httpx.AsyncClient(
base_url=self._base_url,
cookies=self._cookies,
headers=self._headers,
timeout=self._timeout,
verify=self._verify_ssl,
follow_redirects=self._follow_redirects,
**self._httpx_args,
)
return self._async_client
async def __aenter__(self) -> "AuthenticatedClient":
"""Enter a context manager for underlying httpx.AsyncClient—you cannot enter twice (see httpx docs)"""
await self.get_async_httpx_client().__aenter__()
return self
async def __aexit__(self, *args: Any, **kwargs: Any) -> None:
"""Exit a context manager for underlying httpx.AsyncClient (see httpx docs)"""
await self.get_async_httpx_client().__aexit__(*args, **kwargs)

View file

@ -1,16 +0,0 @@
"""Contains shared errors types that can be raised from API functions"""
class UnexpectedStatus(Exception):
"""Raised by api functions when the response status an undocumented status and Client.raise_on_unexpected_status is True"""
def __init__(self, status_code: int, content: bytes):
self.status_code = status_code
self.content = content
super().__init__(
f"Unexpected status code: {status_code}\n\nResponse content:\n{content.decode(errors='ignore')}"
)
__all__ = ["UnexpectedStatus"]

View file

@ -1,65 +0,0 @@
"""Contains all the data models used in inputs/outputs"""
from .add_background_request import AddBackgroundRequest
from .agent_list_item import AgentListItem
from .agent_list_response import AgentListResponse
from .agent_profile_response import AgentProfileResponse
from .background_response import BackgroundResponse
from .batch_put_async_response import BatchPutAsyncResponse
from .batch_put_request import BatchPutRequest
from .batch_put_response import BatchPutResponse
from .create_agent_request import CreateAgentRequest
from .document_response import DocumentResponse
from .graph_data_response import GraphDataResponse
from .graph_data_response_edges_item import GraphDataResponseEdgesItem
from .graph_data_response_nodes_item import GraphDataResponseNodesItem
from .graph_data_response_table_rows_item import GraphDataResponseTableRowsItem
from .http_validation_error import HTTPValidationError
from .list_documents_response import ListDocumentsResponse
from .list_documents_response_items_item import ListDocumentsResponseItemsItem
from .list_memory_units_response import ListMemoryUnitsResponse
from .list_memory_units_response_items_item import ListMemoryUnitsResponseItemsItem
from .memory_item import MemoryItem
from .personality_traits import PersonalityTraits
from .search_request import SearchRequest
from .search_response import SearchResponse
from .search_response_trace_type_0 import SearchResponseTraceType0
from .search_result import SearchResult
from .think_fact import ThinkFact
from .think_request import ThinkRequest
from .think_response import ThinkResponse
from .update_personality_request import UpdatePersonalityRequest
from .validation_error import ValidationError
__all__ = (
"AddBackgroundRequest",
"AgentListItem",
"AgentListResponse",
"AgentProfileResponse",
"BackgroundResponse",
"BatchPutAsyncResponse",
"BatchPutRequest",
"BatchPutResponse",
"CreateAgentRequest",
"DocumentResponse",
"GraphDataResponse",
"GraphDataResponseEdgesItem",
"GraphDataResponseNodesItem",
"GraphDataResponseTableRowsItem",
"HTTPValidationError",
"ListDocumentsResponse",
"ListDocumentsResponseItemsItem",
"ListMemoryUnitsResponse",
"ListMemoryUnitsResponseItemsItem",
"MemoryItem",
"PersonalityTraits",
"SearchRequest",
"SearchResponse",
"SearchResponseTraceType0",
"SearchResult",
"ThinkFact",
"ThinkRequest",
"ThinkResponse",
"UpdatePersonalityRequest",
"ValidationError",
)

View file

@ -1,77 +0,0 @@
from __future__ import annotations
from collections.abc import Mapping
from typing import Any, TypeVar
from attrs import define as _attrs_define
from attrs import field as _attrs_field
from ..types import UNSET, Unset
T = TypeVar("T", bound="AddBackgroundRequest")
@_attrs_define
class AddBackgroundRequest:
"""Request model for adding/merging background information.
Example:
{'content': 'I was born in Texas', 'update_personality': True}
Attributes:
content (str): New background information to add or merge
update_personality (bool | Unset): If true, infer Big Five personality traits from the merged background
(default: true) Default: True.
"""
content: str
update_personality: bool | Unset = True
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
content = self.content
update_personality = self.update_personality
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"content": content,
}
)
if update_personality is not UNSET:
field_dict["update_personality"] = update_personality
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
d = dict(src_dict)
content = d.pop("content")
update_personality = d.pop("update_personality", UNSET)
add_background_request = cls(
content=content,
update_personality=update_personality,
)
add_background_request.additional_properties = d
return add_background_request
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View file

@ -1,127 +0,0 @@
from __future__ import annotations
from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, TypeVar, cast
from attrs import define as _attrs_define
from attrs import field as _attrs_field
from ..types import UNSET, Unset
if TYPE_CHECKING:
from ..models.personality_traits import PersonalityTraits
T = TypeVar("T", bound="AgentListItem")
@_attrs_define
class AgentListItem:
"""Agent list item with profile summary.
Attributes:
agent_id (str):
personality (PersonalityTraits): Personality traits based on Big Five model. Example: {'agreeableness': 0.7,
'bias_strength': 0.7, 'conscientiousness': 0.6, 'extraversion': 0.5, 'neuroticism': 0.3, 'openness': 0.8}.
background (str):
created_at (None | str | Unset):
updated_at (None | str | Unset):
"""
agent_id: str
personality: PersonalityTraits
background: str
created_at: None | str | Unset = UNSET
updated_at: None | str | Unset = UNSET
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
agent_id = self.agent_id
personality = self.personality.to_dict()
background = self.background
created_at: None | str | Unset
if isinstance(self.created_at, Unset):
created_at = UNSET
else:
created_at = self.created_at
updated_at: None | str | Unset
if isinstance(self.updated_at, Unset):
updated_at = UNSET
else:
updated_at = self.updated_at
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"agent_id": agent_id,
"personality": personality,
"background": background,
}
)
if created_at is not UNSET:
field_dict["created_at"] = created_at
if updated_at is not UNSET:
field_dict["updated_at"] = updated_at
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
from ..models.personality_traits import PersonalityTraits
d = dict(src_dict)
agent_id = d.pop("agent_id")
personality = PersonalityTraits.from_dict(d.pop("personality"))
background = d.pop("background")
def _parse_created_at(data: object) -> None | str | Unset:
if data is None:
return data
if isinstance(data, Unset):
return data
return cast(None | str | Unset, data)
created_at = _parse_created_at(d.pop("created_at", UNSET))
def _parse_updated_at(data: object) -> None | str | Unset:
if data is None:
return data
if isinstance(data, Unset):
return data
return cast(None | str | Unset, data)
updated_at = _parse_updated_at(d.pop("updated_at", UNSET))
agent_list_item = cls(
agent_id=agent_id,
personality=personality,
background=background,
created_at=created_at,
updated_at=updated_at,
)
agent_list_item.additional_properties = d
return agent_list_item
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View file

@ -1,81 +0,0 @@
from __future__ import annotations
from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, TypeVar
from attrs import define as _attrs_define
from attrs import field as _attrs_field
if TYPE_CHECKING:
from ..models.agent_list_item import AgentListItem
T = TypeVar("T", bound="AgentListResponse")
@_attrs_define
class AgentListResponse:
"""Response model for listing all agents.
Example:
{'agents': [{'agent_id': 'user123', 'background': 'I am a software engineer', 'created_at':
'2024-01-15T10:30:00Z', 'personality': {'agreeableness': 0.5, 'bias_strength': 0.5, 'conscientiousness': 0.5,
'extraversion': 0.5, 'neuroticism': 0.5, 'openness': 0.5}, 'updated_at': '2024-01-16T14:20:00Z'}]}
Attributes:
agents (list[AgentListItem]):
"""
agents: list[AgentListItem]
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
agents = []
for agents_item_data in self.agents:
agents_item = agents_item_data.to_dict()
agents.append(agents_item)
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"agents": agents,
}
)
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
from ..models.agent_list_item import AgentListItem
d = dict(src_dict)
agents = []
_agents = d.pop("agents")
for agents_item_data in _agents:
agents_item = AgentListItem.from_dict(agents_item_data)
agents.append(agents_item)
agent_list_response = cls(
agents=agents,
)
agent_list_response.additional_properties = d
return agent_list_response
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View file

@ -1,90 +0,0 @@
from __future__ import annotations
from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, TypeVar
from attrs import define as _attrs_define
from attrs import field as _attrs_field
if TYPE_CHECKING:
from ..models.personality_traits import PersonalityTraits
T = TypeVar("T", bound="AgentProfileResponse")
@_attrs_define
class AgentProfileResponse:
"""Response model for agent profile.
Example:
{'agent_id': 'user123', 'background': 'I am a software engineer with 10 years of experience in startups',
'personality': {'agreeableness': 0.7, 'bias_strength': 0.7, 'conscientiousness': 0.6, 'extraversion': 0.5,
'neuroticism': 0.3, 'openness': 0.8}}
Attributes:
agent_id (str):
personality (PersonalityTraits): Personality traits based on Big Five model. Example: {'agreeableness': 0.7,
'bias_strength': 0.7, 'conscientiousness': 0.6, 'extraversion': 0.5, 'neuroticism': 0.3, 'openness': 0.8}.
background (str):
"""
agent_id: str
personality: PersonalityTraits
background: str
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
agent_id = self.agent_id
personality = self.personality.to_dict()
background = self.background
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"agent_id": agent_id,
"personality": personality,
"background": background,
}
)
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
from ..models.personality_traits import PersonalityTraits
d = dict(src_dict)
agent_id = d.pop("agent_id")
personality = PersonalityTraits.from_dict(d.pop("personality"))
background = d.pop("background")
agent_profile_response = cls(
agent_id=agent_id,
personality=personality,
background=background,
)
agent_profile_response.additional_properties = d
return agent_profile_response
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View file

@ -1,107 +0,0 @@
from __future__ import annotations
from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, TypeVar, cast
from attrs import define as _attrs_define
from attrs import field as _attrs_field
from ..types import UNSET, Unset
if TYPE_CHECKING:
from ..models.personality_traits import PersonalityTraits
T = TypeVar("T", bound="BackgroundResponse")
@_attrs_define
class BackgroundResponse:
"""Response model for background update.
Example:
{'background': 'I was born in Texas. I am a software engineer with 10 years of experience.', 'personality':
{'agreeableness': 0.8, 'bias_strength': 0.6, 'conscientiousness': 0.6, 'extraversion': 0.5, 'neuroticism': 0.4,
'openness': 0.7}}
Attributes:
background (str):
personality (None | PersonalityTraits | Unset):
"""
background: str
personality: None | PersonalityTraits | Unset = UNSET
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
from ..models.personality_traits import PersonalityTraits
background = self.background
personality: dict[str, Any] | None | Unset
if isinstance(self.personality, Unset):
personality = UNSET
elif isinstance(self.personality, PersonalityTraits):
personality = self.personality.to_dict()
else:
personality = self.personality
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"background": background,
}
)
if personality is not UNSET:
field_dict["personality"] = personality
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
from ..models.personality_traits import PersonalityTraits
d = dict(src_dict)
background = d.pop("background")
def _parse_personality(data: object) -> None | PersonalityTraits | Unset:
if data is None:
return data
if isinstance(data, Unset):
return data
try:
if not isinstance(data, dict):
raise TypeError()
personality_type_0 = PersonalityTraits.from_dict(data)
return personality_type_0
except (TypeError, ValueError, AttributeError, KeyError):
pass
return cast(None | PersonalityTraits | Unset, data)
personality = _parse_personality(d.pop("personality", UNSET))
background_response = cls(
background=background,
personality=personality,
)
background_response.additional_properties = d
return background_response
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View file

@ -1,120 +0,0 @@
from __future__ import annotations
from collections.abc import Mapping
from typing import Any, TypeVar, cast
from attrs import define as _attrs_define
from attrs import field as _attrs_field
from ..types import UNSET, Unset
T = TypeVar("T", bound="BatchPutAsyncResponse")
@_attrs_define
class BatchPutAsyncResponse:
"""Response model for async batch put endpoint.
Example:
{'agent_id': 'user123', 'document_id': 'conversation_123', 'items_count': 2, 'message': 'Batch put task queued
for background processing', 'queued': True, 'success': True}
Attributes:
success (bool):
message (str):
agent_id (str):
items_count (int):
queued (bool):
document_id (None | str | Unset):
"""
success: bool
message: str
agent_id: str
items_count: int
queued: bool
document_id: None | str | Unset = UNSET
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
success = self.success
message = self.message
agent_id = self.agent_id
items_count = self.items_count
queued = self.queued
document_id: None | str | Unset
if isinstance(self.document_id, Unset):
document_id = UNSET
else:
document_id = self.document_id
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"success": success,
"message": message,
"agent_id": agent_id,
"items_count": items_count,
"queued": queued,
}
)
if document_id is not UNSET:
field_dict["document_id"] = document_id
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
d = dict(src_dict)
success = d.pop("success")
message = d.pop("message")
agent_id = d.pop("agent_id")
items_count = d.pop("items_count")
queued = d.pop("queued")
def _parse_document_id(data: object) -> None | str | Unset:
if data is None:
return data
if isinstance(data, Unset):
return data
return cast(None | str | Unset, data)
document_id = _parse_document_id(d.pop("document_id", UNSET))
batch_put_async_response = cls(
success=success,
message=message,
agent_id=agent_id,
items_count=items_count,
queued=queued,
document_id=document_id,
)
batch_put_async_response.additional_properties = d
return batch_put_async_response
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View file

@ -1,102 +0,0 @@
from __future__ import annotations
from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, TypeVar, cast
from attrs import define as _attrs_define
from attrs import field as _attrs_field
from ..types import UNSET, Unset
if TYPE_CHECKING:
from ..models.memory_item import MemoryItem
T = TypeVar("T", bound="BatchPutRequest")
@_attrs_define
class BatchPutRequest:
"""Request model for batch put endpoint.
Example:
{'document_id': 'conversation_123', 'items': [{'content': 'Alice works at Google', 'context': 'work'},
{'content': 'Bob went hiking yesterday', 'event_date': '2024-01-15T10:00:00Z'}]}
Attributes:
items (list[MemoryItem]):
document_id (None | str | Unset):
"""
items: list[MemoryItem]
document_id: None | str | Unset = UNSET
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
items = []
for items_item_data in self.items:
items_item = items_item_data.to_dict()
items.append(items_item)
document_id: None | str | Unset
if isinstance(self.document_id, Unset):
document_id = UNSET
else:
document_id = self.document_id
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"items": items,
}
)
if document_id is not UNSET:
field_dict["document_id"] = document_id
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
from ..models.memory_item import MemoryItem
d = dict(src_dict)
items = []
_items = d.pop("items")
for items_item_data in _items:
items_item = MemoryItem.from_dict(items_item_data)
items.append(items_item)
def _parse_document_id(data: object) -> None | str | Unset:
if data is None:
return data
if isinstance(data, Unset):
return data
return cast(None | str | Unset, data)
document_id = _parse_document_id(d.pop("document_id", UNSET))
batch_put_request = cls(
items=items,
document_id=document_id,
)
batch_put_request.additional_properties = d
return batch_put_request
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View file

@ -1,112 +0,0 @@
from __future__ import annotations
from collections.abc import Mapping
from typing import Any, TypeVar, cast
from attrs import define as _attrs_define
from attrs import field as _attrs_field
from ..types import UNSET, Unset
T = TypeVar("T", bound="BatchPutResponse")
@_attrs_define
class BatchPutResponse:
"""Response model for batch put endpoint.
Example:
{'agent_id': 'user123', 'document_id': 'conversation_123', 'items_count': 2, 'message': 'Successfully stored 2
memory items', 'success': True}
Attributes:
success (bool):
message (str):
agent_id (str):
items_count (int):
document_id (None | str | Unset):
"""
success: bool
message: str
agent_id: str
items_count: int
document_id: None | str | Unset = UNSET
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
success = self.success
message = self.message
agent_id = self.agent_id
items_count = self.items_count
document_id: None | str | Unset
if isinstance(self.document_id, Unset):
document_id = UNSET
else:
document_id = self.document_id
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"success": success,
"message": message,
"agent_id": agent_id,
"items_count": items_count,
}
)
if document_id is not UNSET:
field_dict["document_id"] = document_id
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
d = dict(src_dict)
success = d.pop("success")
message = d.pop("message")
agent_id = d.pop("agent_id")
items_count = d.pop("items_count")
def _parse_document_id(data: object) -> None | str | Unset:
if data is None:
return data
if isinstance(data, Unset):
return data
return cast(None | str | Unset, data)
document_id = _parse_document_id(d.pop("document_id", UNSET))
batch_put_response = cls(
success=success,
message=message,
agent_id=agent_id,
items_count=items_count,
document_id=document_id,
)
batch_put_response.additional_properties = d
return batch_put_response
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View file

@ -1,116 +0,0 @@
from __future__ import annotations
from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, TypeVar, cast
from attrs import define as _attrs_define
from attrs import field as _attrs_field
from ..types import UNSET, Unset
if TYPE_CHECKING:
from ..models.personality_traits import PersonalityTraits
T = TypeVar("T", bound="CreateAgentRequest")
@_attrs_define
class CreateAgentRequest:
"""Request model for creating/updating an agent.
Example:
{'background': 'I am a creative software engineer with 10 years of experience', 'personality': {'agreeableness':
0.7, 'bias_strength': 0.7, 'conscientiousness': 0.6, 'extraversion': 0.5, 'neuroticism': 0.3, 'openness': 0.8}}
Attributes:
personality (None | PersonalityTraits | Unset):
background (None | str | Unset):
"""
personality: None | PersonalityTraits | Unset = UNSET
background: None | str | Unset = UNSET
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
from ..models.personality_traits import PersonalityTraits
personality: dict[str, Any] | None | Unset
if isinstance(self.personality, Unset):
personality = UNSET
elif isinstance(self.personality, PersonalityTraits):
personality = self.personality.to_dict()
else:
personality = self.personality
background: None | str | Unset
if isinstance(self.background, Unset):
background = UNSET
else:
background = self.background
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update({})
if personality is not UNSET:
field_dict["personality"] = personality
if background is not UNSET:
field_dict["background"] = background
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
from ..models.personality_traits import PersonalityTraits
d = dict(src_dict)
def _parse_personality(data: object) -> None | PersonalityTraits | Unset:
if data is None:
return data
if isinstance(data, Unset):
return data
try:
if not isinstance(data, dict):
raise TypeError()
personality_type_0 = PersonalityTraits.from_dict(data)
return personality_type_0
except (TypeError, ValueError, AttributeError, KeyError):
pass
return cast(None | PersonalityTraits | Unset, data)
personality = _parse_personality(d.pop("personality", UNSET))
def _parse_background(data: object) -> None | str | Unset:
if data is None:
return data
if isinstance(data, Unset):
return data
return cast(None | str | Unset, data)
background = _parse_background(d.pop("background", UNSET))
create_agent_request = cls(
personality=personality,
background=background,
)
create_agent_request.additional_properties = d
return create_agent_request
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View file

@ -1,120 +0,0 @@
from __future__ import annotations
from collections.abc import Mapping
from typing import Any, TypeVar, cast
from attrs import define as _attrs_define
from attrs import field as _attrs_field
T = TypeVar("T", bound="DocumentResponse")
@_attrs_define
class DocumentResponse:
"""Response model for get document endpoint.
Example:
{'agent_id': 'user123', 'content_hash': 'abc123', 'created_at': '2024-01-15T10:30:00Z', 'id': 'session_1',
'memory_unit_count': 15, 'original_text': 'Full document text here...', 'updated_at': '2024-01-15T10:30:00Z'}
Attributes:
id (str):
agent_id (str):
original_text (str):
content_hash (None | str):
created_at (str):
updated_at (str):
memory_unit_count (int):
"""
id: str
agent_id: str
original_text: str
content_hash: None | str
created_at: str
updated_at: str
memory_unit_count: int
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
id = self.id
agent_id = self.agent_id
original_text = self.original_text
content_hash: None | str
content_hash = self.content_hash
created_at = self.created_at
updated_at = self.updated_at
memory_unit_count = self.memory_unit_count
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"id": id,
"agent_id": agent_id,
"original_text": original_text,
"content_hash": content_hash,
"created_at": created_at,
"updated_at": updated_at,
"memory_unit_count": memory_unit_count,
}
)
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
d = dict(src_dict)
id = d.pop("id")
agent_id = d.pop("agent_id")
original_text = d.pop("original_text")
def _parse_content_hash(data: object) -> None | str:
if data is None:
return data
return cast(None | str, data)
content_hash = _parse_content_hash(d.pop("content_hash"))
created_at = d.pop("created_at")
updated_at = d.pop("updated_at")
memory_unit_count = d.pop("memory_unit_count")
document_response = cls(
id=id,
agent_id=agent_id,
original_text=original_text,
content_hash=content_hash,
created_at=created_at,
updated_at=updated_at,
memory_unit_count=memory_unit_count,
)
document_response.additional_properties = d
return document_response
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View file

@ -1,126 +0,0 @@
from __future__ import annotations
from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, TypeVar
from attrs import define as _attrs_define
from attrs import field as _attrs_field
if TYPE_CHECKING:
from ..models.graph_data_response_edges_item import GraphDataResponseEdgesItem
from ..models.graph_data_response_nodes_item import GraphDataResponseNodesItem
from ..models.graph_data_response_table_rows_item import GraphDataResponseTableRowsItem
T = TypeVar("T", bound="GraphDataResponse")
@_attrs_define
class GraphDataResponse:
"""Response model for graph data endpoint.
Example:
{'edges': [{'from': '1', 'to': '2', 'type': 'semantic', 'weight': 0.8}], 'nodes': [{'id': '1', 'label': 'Alice
works at Google', 'type': 'world'}, {'id': '2', 'label': 'Bob went hiking', 'type': 'world'}], 'table_rows':
[{'context': 'Work info', 'date': '2024-01-15 10:30', 'entities': 'Alice (PERSON), Google (ORGANIZATION)', 'id':
'abc12345...', 'text': 'Alice works at Google'}], 'total_units': 2}
Attributes:
nodes (list[GraphDataResponseNodesItem]):
edges (list[GraphDataResponseEdgesItem]):
table_rows (list[GraphDataResponseTableRowsItem]):
total_units (int):
"""
nodes: list[GraphDataResponseNodesItem]
edges: list[GraphDataResponseEdgesItem]
table_rows: list[GraphDataResponseTableRowsItem]
total_units: int
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
nodes = []
for nodes_item_data in self.nodes:
nodes_item = nodes_item_data.to_dict()
nodes.append(nodes_item)
edges = []
for edges_item_data in self.edges:
edges_item = edges_item_data.to_dict()
edges.append(edges_item)
table_rows = []
for table_rows_item_data in self.table_rows:
table_rows_item = table_rows_item_data.to_dict()
table_rows.append(table_rows_item)
total_units = self.total_units
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"nodes": nodes,
"edges": edges,
"table_rows": table_rows,
"total_units": total_units,
}
)
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
from ..models.graph_data_response_edges_item import GraphDataResponseEdgesItem
from ..models.graph_data_response_nodes_item import GraphDataResponseNodesItem
from ..models.graph_data_response_table_rows_item import GraphDataResponseTableRowsItem
d = dict(src_dict)
nodes = []
_nodes = d.pop("nodes")
for nodes_item_data in _nodes:
nodes_item = GraphDataResponseNodesItem.from_dict(nodes_item_data)
nodes.append(nodes_item)
edges = []
_edges = d.pop("edges")
for edges_item_data in _edges:
edges_item = GraphDataResponseEdgesItem.from_dict(edges_item_data)
edges.append(edges_item)
table_rows = []
_table_rows = d.pop("table_rows")
for table_rows_item_data in _table_rows:
table_rows_item = GraphDataResponseTableRowsItem.from_dict(table_rows_item_data)
table_rows.append(table_rows_item)
total_units = d.pop("total_units")
graph_data_response = cls(
nodes=nodes,
edges=edges,
table_rows=table_rows,
total_units=total_units,
)
graph_data_response.additional_properties = d
return graph_data_response
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View file

@ -1,46 +0,0 @@
from __future__ import annotations
from collections.abc import Mapping
from typing import Any, TypeVar
from attrs import define as _attrs_define
from attrs import field as _attrs_field
T = TypeVar("T", bound="GraphDataResponseEdgesItem")
@_attrs_define
class GraphDataResponseEdgesItem:
""" """
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
d = dict(src_dict)
graph_data_response_edges_item = cls()
graph_data_response_edges_item.additional_properties = d
return graph_data_response_edges_item
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View file

@ -1,46 +0,0 @@
from __future__ import annotations
from collections.abc import Mapping
from typing import Any, TypeVar
from attrs import define as _attrs_define
from attrs import field as _attrs_field
T = TypeVar("T", bound="GraphDataResponseNodesItem")
@_attrs_define
class GraphDataResponseNodesItem:
""" """
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
d = dict(src_dict)
graph_data_response_nodes_item = cls()
graph_data_response_nodes_item.additional_properties = d
return graph_data_response_nodes_item
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View file

@ -1,46 +0,0 @@
from __future__ import annotations
from collections.abc import Mapping
from typing import Any, TypeVar
from attrs import define as _attrs_define
from attrs import field as _attrs_field
T = TypeVar("T", bound="GraphDataResponseTableRowsItem")
@_attrs_define
class GraphDataResponseTableRowsItem:
""" """
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
d = dict(src_dict)
graph_data_response_table_rows_item = cls()
graph_data_response_table_rows_item.additional_properties = d
return graph_data_response_table_rows_item
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View file

@ -1,79 +0,0 @@
from __future__ import annotations
from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, TypeVar
from attrs import define as _attrs_define
from attrs import field as _attrs_field
from ..types import UNSET, Unset
if TYPE_CHECKING:
from ..models.validation_error import ValidationError
T = TypeVar("T", bound="HTTPValidationError")
@_attrs_define
class HTTPValidationError:
"""
Attributes:
detail (list[ValidationError] | Unset):
"""
detail: list[ValidationError] | Unset = UNSET
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
detail: list[dict[str, Any]] | Unset = UNSET
if not isinstance(self.detail, Unset):
detail = []
for detail_item_data in self.detail:
detail_item = detail_item_data.to_dict()
detail.append(detail_item)
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update({})
if detail is not UNSET:
field_dict["detail"] = detail
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
from ..models.validation_error import ValidationError
d = dict(src_dict)
_detail = d.pop("detail", UNSET)
detail: list[ValidationError] | Unset = UNSET
if _detail is not UNSET:
detail = []
for detail_item_data in _detail:
detail_item = ValidationError.from_dict(detail_item_data)
detail.append(detail_item)
http_validation_error = cls(
detail=detail,
)
http_validation_error.additional_properties = d
return http_validation_error
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View file

@ -1,105 +0,0 @@
from __future__ import annotations
from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, TypeVar
from attrs import define as _attrs_define
from attrs import field as _attrs_field
if TYPE_CHECKING:
from ..models.list_documents_response_items_item import ListDocumentsResponseItemsItem
T = TypeVar("T", bound="ListDocumentsResponse")
@_attrs_define
class ListDocumentsResponse:
"""Response model for list documents endpoint.
Example:
{'items': [{'agent_id': 'user123', 'content_hash': 'abc123', 'created_at': '2024-01-15T10:30:00Z', 'id':
'session_1', 'memory_unit_count': 15, 'text_length': 5420, 'updated_at': '2024-01-15T10:30:00Z'}], 'limit': 100,
'offset': 0, 'total': 50}
Attributes:
items (list[ListDocumentsResponseItemsItem]):
total (int):
limit (int):
offset (int):
"""
items: list[ListDocumentsResponseItemsItem]
total: int
limit: int
offset: int
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
items = []
for items_item_data in self.items:
items_item = items_item_data.to_dict()
items.append(items_item)
total = self.total
limit = self.limit
offset = self.offset
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"items": items,
"total": total,
"limit": limit,
"offset": offset,
}
)
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
from ..models.list_documents_response_items_item import ListDocumentsResponseItemsItem
d = dict(src_dict)
items = []
_items = d.pop("items")
for items_item_data in _items:
items_item = ListDocumentsResponseItemsItem.from_dict(items_item_data)
items.append(items_item)
total = d.pop("total")
limit = d.pop("limit")
offset = d.pop("offset")
list_documents_response = cls(
items=items,
total=total,
limit=limit,
offset=offset,
)
list_documents_response.additional_properties = d
return list_documents_response
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View file

@ -1,46 +0,0 @@
from __future__ import annotations
from collections.abc import Mapping
from typing import Any, TypeVar
from attrs import define as _attrs_define
from attrs import field as _attrs_field
T = TypeVar("T", bound="ListDocumentsResponseItemsItem")
@_attrs_define
class ListDocumentsResponseItemsItem:
""" """
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
d = dict(src_dict)
list_documents_response_items_item = cls()
list_documents_response_items_item.additional_properties = d
return list_documents_response_items_item
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View file

@ -1,105 +0,0 @@
from __future__ import annotations
from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, TypeVar
from attrs import define as _attrs_define
from attrs import field as _attrs_field
if TYPE_CHECKING:
from ..models.list_memory_units_response_items_item import ListMemoryUnitsResponseItemsItem
T = TypeVar("T", bound="ListMemoryUnitsResponse")
@_attrs_define
class ListMemoryUnitsResponse:
"""Response model for list memory units endpoint.
Example:
{'items': [{'context': 'Work conversation', 'date': '2024-01-15T10:30:00Z', 'entities': 'Alice (PERSON), Google
(ORGANIZATION)', 'fact_type': 'world', 'id': '550e8400-e29b-41d4-a716-446655440000', 'text': 'Alice works at
Google on the AI team'}], 'limit': 100, 'offset': 0, 'total': 150}
Attributes:
items (list[ListMemoryUnitsResponseItemsItem]):
total (int):
limit (int):
offset (int):
"""
items: list[ListMemoryUnitsResponseItemsItem]
total: int
limit: int
offset: int
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
items = []
for items_item_data in self.items:
items_item = items_item_data.to_dict()
items.append(items_item)
total = self.total
limit = self.limit
offset = self.offset
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"items": items,
"total": total,
"limit": limit,
"offset": offset,
}
)
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
from ..models.list_memory_units_response_items_item import ListMemoryUnitsResponseItemsItem
d = dict(src_dict)
items = []
_items = d.pop("items")
for items_item_data in _items:
items_item = ListMemoryUnitsResponseItemsItem.from_dict(items_item_data)
items.append(items_item)
total = d.pop("total")
limit = d.pop("limit")
offset = d.pop("offset")
list_memory_units_response = cls(
items=items,
total=total,
limit=limit,
offset=offset,
)
list_memory_units_response.additional_properties = d
return list_memory_units_response
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View file

@ -1,46 +0,0 @@
from __future__ import annotations
from collections.abc import Mapping
from typing import Any, TypeVar
from attrs import define as _attrs_define
from attrs import field as _attrs_field
T = TypeVar("T", bound="ListMemoryUnitsResponseItemsItem")
@_attrs_define
class ListMemoryUnitsResponseItemsItem:
""" """
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
d = dict(src_dict)
list_memory_units_response_items_item = cls()
list_memory_units_response_items_item.additional_properties = d
return list_memory_units_response_items_item
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View file

@ -1,120 +0,0 @@
from __future__ import annotations
import datetime
from collections.abc import Mapping
from typing import Any, TypeVar, cast
from attrs import define as _attrs_define
from attrs import field as _attrs_field
from dateutil.parser import isoparse
from ..types import UNSET, Unset
T = TypeVar("T", bound="MemoryItem")
@_attrs_define
class MemoryItem:
"""Single memory item for batch put.
Example:
{'content': "Alice mentioned she's working on a new ML model", 'context': 'team meeting', 'event_date':
'2024-01-15T10:30:00Z'}
Attributes:
content (str):
event_date (datetime.datetime | None | Unset):
context (None | str | Unset):
"""
content: str
event_date: datetime.datetime | None | Unset = UNSET
context: None | str | Unset = UNSET
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
content = self.content
event_date: None | str | Unset
if isinstance(self.event_date, Unset):
event_date = UNSET
elif isinstance(self.event_date, datetime.datetime):
event_date = self.event_date.isoformat()
else:
event_date = self.event_date
context: None | str | Unset
if isinstance(self.context, Unset):
context = UNSET
else:
context = self.context
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"content": content,
}
)
if event_date is not UNSET:
field_dict["event_date"] = event_date
if context is not UNSET:
field_dict["context"] = context
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
d = dict(src_dict)
content = d.pop("content")
def _parse_event_date(data: object) -> datetime.datetime | None | Unset:
if data is None:
return data
if isinstance(data, Unset):
return data
try:
if not isinstance(data, str):
raise TypeError()
event_date_type_0 = isoparse(data)
return event_date_type_0
except (TypeError, ValueError, AttributeError, KeyError):
pass
return cast(datetime.datetime | None | Unset, data)
event_date = _parse_event_date(d.pop("event_date", UNSET))
def _parse_context(data: object) -> None | str | Unset:
if data is None:
return data
if isinstance(data, Unset):
return data
return cast(None | str | Unset, data)
context = _parse_context(d.pop("context", UNSET))
memory_item = cls(
content=content,
event_date=event_date,
context=context,
)
memory_item.additional_properties = d
return memory_item
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View file

@ -1,106 +0,0 @@
from __future__ import annotations
from collections.abc import Mapping
from typing import Any, TypeVar
from attrs import define as _attrs_define
from attrs import field as _attrs_field
T = TypeVar("T", bound="PersonalityTraits")
@_attrs_define
class PersonalityTraits:
"""Personality traits based on Big Five model.
Example:
{'agreeableness': 0.7, 'bias_strength': 0.7, 'conscientiousness': 0.6, 'extraversion': 0.5, 'neuroticism': 0.3,
'openness': 0.8}
Attributes:
openness (float): Openness to experience (0-1)
conscientiousness (float): Conscientiousness (0-1)
extraversion (float): Extraversion (0-1)
agreeableness (float): Agreeableness (0-1)
neuroticism (float): Neuroticism (0-1)
bias_strength (float): How strongly personality influences opinions (0-1)
"""
openness: float
conscientiousness: float
extraversion: float
agreeableness: float
neuroticism: float
bias_strength: float
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
openness = self.openness
conscientiousness = self.conscientiousness
extraversion = self.extraversion
agreeableness = self.agreeableness
neuroticism = self.neuroticism
bias_strength = self.bias_strength
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"openness": openness,
"conscientiousness": conscientiousness,
"extraversion": extraversion,
"agreeableness": agreeableness,
"neuroticism": neuroticism,
"bias_strength": bias_strength,
}
)
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
d = dict(src_dict)
openness = d.pop("openness")
conscientiousness = d.pop("conscientiousness")
extraversion = d.pop("extraversion")
agreeableness = d.pop("agreeableness")
neuroticism = d.pop("neuroticism")
bias_strength = d.pop("bias_strength")
personality_traits = cls(
openness=openness,
conscientiousness=conscientiousness,
extraversion=extraversion,
agreeableness=agreeableness,
neuroticism=neuroticism,
bias_strength=bias_strength,
)
personality_traits.additional_properties = d
return personality_traits
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View file

@ -1,155 +0,0 @@
from __future__ import annotations
from collections.abc import Mapping
from typing import Any, TypeVar, cast
from attrs import define as _attrs_define
from attrs import field as _attrs_field
from ..types import UNSET, Unset
T = TypeVar("T", bound="SearchRequest")
@_attrs_define
class SearchRequest:
"""Request model for search endpoint.
Example:
{'fact_type': ['world', 'agent'], 'max_tokens': 4096, 'query': 'What did Alice say about machine learning?',
'question_date': '2023-05-30T23:40:00', 'reranker': 'heuristic', 'thinking_budget': 100, 'trace': True}
Attributes:
query (str):
fact_type (list[str] | None | Unset):
thinking_budget (int | Unset): Default: 100.
max_tokens (int | Unset): Default: 4096.
reranker (str | Unset): Default: 'heuristic'.
trace (bool | Unset): Default: False.
question_date (None | str | Unset):
"""
query: str
fact_type: list[str] | None | Unset = UNSET
thinking_budget: int | Unset = 100
max_tokens: int | Unset = 4096
reranker: str | Unset = "heuristic"
trace: bool | Unset = False
question_date: None | str | Unset = UNSET
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
query = self.query
fact_type: list[str] | None | Unset
if isinstance(self.fact_type, Unset):
fact_type = UNSET
elif isinstance(self.fact_type, list):
fact_type = self.fact_type
else:
fact_type = self.fact_type
thinking_budget = self.thinking_budget
max_tokens = self.max_tokens
reranker = self.reranker
trace = self.trace
question_date: None | str | Unset
if isinstance(self.question_date, Unset):
question_date = UNSET
else:
question_date = self.question_date
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"query": query,
}
)
if fact_type is not UNSET:
field_dict["fact_type"] = fact_type
if thinking_budget is not UNSET:
field_dict["thinking_budget"] = thinking_budget
if max_tokens is not UNSET:
field_dict["max_tokens"] = max_tokens
if reranker is not UNSET:
field_dict["reranker"] = reranker
if trace is not UNSET:
field_dict["trace"] = trace
if question_date is not UNSET:
field_dict["question_date"] = question_date
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
d = dict(src_dict)
query = d.pop("query")
def _parse_fact_type(data: object) -> list[str] | None | Unset:
if data is None:
return data
if isinstance(data, Unset):
return data
try:
if not isinstance(data, list):
raise TypeError()
fact_type_type_0 = cast(list[str], data)
return fact_type_type_0
except (TypeError, ValueError, AttributeError, KeyError):
pass
return cast(list[str] | None | Unset, data)
fact_type = _parse_fact_type(d.pop("fact_type", UNSET))
thinking_budget = d.pop("thinking_budget", UNSET)
max_tokens = d.pop("max_tokens", UNSET)
reranker = d.pop("reranker", UNSET)
trace = d.pop("trace", UNSET)
def _parse_question_date(data: object) -> None | str | Unset:
if data is None:
return data
if isinstance(data, Unset):
return data
return cast(None | str | Unset, data)
question_date = _parse_question_date(d.pop("question_date", UNSET))
search_request = cls(
query=query,
fact_type=fact_type,
thinking_budget=thinking_budget,
max_tokens=max_tokens,
reranker=reranker,
trace=trace,
question_date=question_date,
)
search_request.additional_properties = d
return search_request
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View file

@ -1,117 +0,0 @@
from __future__ import annotations
from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, TypeVar, cast
from attrs import define as _attrs_define
from attrs import field as _attrs_field
from ..types import UNSET, Unset
if TYPE_CHECKING:
from ..models.search_response_trace_type_0 import SearchResponseTraceType0
from ..models.search_result import SearchResult
T = TypeVar("T", bound="SearchResponse")
@_attrs_define
class SearchResponse:
"""Response model for search endpoints.
Example:
{'results': [{'activation': 0.95, 'context': 'work info', 'event_date': '2024-01-15T10:30:00Z', 'id':
'123e4567-e89b-12d3-a456-426614174000', 'text': 'Alice works at Google on the AI team', 'type': 'world'}],
'trace': {'num_results': 1, 'query': 'What did Alice say about machine learning?', 'time_seconds': 0.123}}
Attributes:
results (list[SearchResult]):
trace (None | SearchResponseTraceType0 | Unset):
"""
results: list[SearchResult]
trace: None | SearchResponseTraceType0 | Unset = UNSET
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
from ..models.search_response_trace_type_0 import SearchResponseTraceType0
results = []
for results_item_data in self.results:
results_item = results_item_data.to_dict()
results.append(results_item)
trace: dict[str, Any] | None | Unset
if isinstance(self.trace, Unset):
trace = UNSET
elif isinstance(self.trace, SearchResponseTraceType0):
trace = self.trace.to_dict()
else:
trace = self.trace
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"results": results,
}
)
if trace is not UNSET:
field_dict["trace"] = trace
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
from ..models.search_response_trace_type_0 import SearchResponseTraceType0
from ..models.search_result import SearchResult
d = dict(src_dict)
results = []
_results = d.pop("results")
for results_item_data in _results:
results_item = SearchResult.from_dict(results_item_data)
results.append(results_item)
def _parse_trace(data: object) -> None | SearchResponseTraceType0 | Unset:
if data is None:
return data
if isinstance(data, Unset):
return data
try:
if not isinstance(data, dict):
raise TypeError()
trace_type_0 = SearchResponseTraceType0.from_dict(data)
return trace_type_0
except (TypeError, ValueError, AttributeError, KeyError):
pass
return cast(None | SearchResponseTraceType0 | Unset, data)
trace = _parse_trace(d.pop("trace", UNSET))
search_response = cls(
results=results,
trace=trace,
)
search_response.additional_properties = d
return search_response
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View file

@ -1,46 +0,0 @@
from __future__ import annotations
from collections.abc import Mapping
from typing import Any, TypeVar
from attrs import define as _attrs_define
from attrs import field as _attrs_field
T = TypeVar("T", bound="SearchResponseTraceType0")
@_attrs_define
class SearchResponseTraceType0:
""" """
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
d = dict(src_dict)
search_response_trace_type_0 = cls()
search_response_trace_type_0.additional_properties = d
return search_response_trace_type_0
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View file

@ -1,156 +0,0 @@
from __future__ import annotations
from collections.abc import Mapping
from typing import Any, TypeVar, cast
from attrs import define as _attrs_define
from attrs import field as _attrs_field
from ..types import UNSET, Unset
T = TypeVar("T", bound="SearchResult")
@_attrs_define
class SearchResult:
"""Single search result item.
Example:
{'context': 'work info', 'event_date': '2024-01-15T10:30:00Z', 'id': '123e4567-e89b-12d3-a456-426614174000',
'text': 'Alice works at Google on the AI team', 'type': 'world'}
Attributes:
id (str):
text (str):
type_ (None | str | Unset):
activation (float | None | Unset):
context (None | str | Unset):
event_date (None | str | Unset):
"""
id: str
text: str
type_: None | str | Unset = UNSET
activation: float | None | Unset = UNSET
context: None | str | Unset = UNSET
event_date: None | str | Unset = UNSET
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
id = self.id
text = self.text
type_: None | str | Unset
if isinstance(self.type_, Unset):
type_ = UNSET
else:
type_ = self.type_
activation: float | None | Unset
if isinstance(self.activation, Unset):
activation = UNSET
else:
activation = self.activation
context: None | str | Unset
if isinstance(self.context, Unset):
context = UNSET
else:
context = self.context
event_date: None | str | Unset
if isinstance(self.event_date, Unset):
event_date = UNSET
else:
event_date = self.event_date
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"id": id,
"text": text,
}
)
if type_ is not UNSET:
field_dict["type"] = type_
if activation is not UNSET:
field_dict["activation"] = activation
if context is not UNSET:
field_dict["context"] = context
if event_date is not UNSET:
field_dict["event_date"] = event_date
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
d = dict(src_dict)
id = d.pop("id")
text = d.pop("text")
def _parse_type_(data: object) -> None | str | Unset:
if data is None:
return data
if isinstance(data, Unset):
return data
return cast(None | str | Unset, data)
type_ = _parse_type_(d.pop("type", UNSET))
def _parse_activation(data: object) -> float | None | Unset:
if data is None:
return data
if isinstance(data, Unset):
return data
return cast(float | None | Unset, data)
activation = _parse_activation(d.pop("activation", UNSET))
def _parse_context(data: object) -> None | str | Unset:
if data is None:
return data
if isinstance(data, Unset):
return data
return cast(None | str | Unset, data)
context = _parse_context(d.pop("context", UNSET))
def _parse_event_date(data: object) -> None | str | Unset:
if data is None:
return data
if isinstance(data, Unset):
return data
return cast(None | str | Unset, data)
event_date = _parse_event_date(d.pop("event_date", UNSET))
search_result = cls(
id=id,
text=text,
type_=type_,
activation=activation,
context=context,
event_date=event_date,
)
search_result.additional_properties = d
return search_result
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View file

@ -1,168 +0,0 @@
from __future__ import annotations
from collections.abc import Mapping
from typing import Any, TypeVar, cast
from attrs import define as _attrs_define
from attrs import field as _attrs_field
from ..types import UNSET, Unset
T = TypeVar("T", bound="ThinkFact")
@_attrs_define
class ThinkFact:
"""A fact used in think response.
Example:
{'context': 'healthcare discussion', 'event_date': '2024-01-15T10:30:00Z', 'id':
'123e4567-e89b-12d3-a456-426614174000', 'text': 'AI is used in healthcare', 'type': 'world'}
Attributes:
text (str):
id (None | str | Unset):
type_ (None | str | Unset):
activation (float | None | Unset):
context (None | str | Unset):
event_date (None | str | Unset):
"""
text: str
id: None | str | Unset = UNSET
type_: None | str | Unset = UNSET
activation: float | None | Unset = UNSET
context: None | str | Unset = UNSET
event_date: None | str | Unset = UNSET
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
text = self.text
id: None | str | Unset
if isinstance(self.id, Unset):
id = UNSET
else:
id = self.id
type_: None | str | Unset
if isinstance(self.type_, Unset):
type_ = UNSET
else:
type_ = self.type_
activation: float | None | Unset
if isinstance(self.activation, Unset):
activation = UNSET
else:
activation = self.activation
context: None | str | Unset
if isinstance(self.context, Unset):
context = UNSET
else:
context = self.context
event_date: None | str | Unset
if isinstance(self.event_date, Unset):
event_date = UNSET
else:
event_date = self.event_date
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"text": text,
}
)
if id is not UNSET:
field_dict["id"] = id
if type_ is not UNSET:
field_dict["type"] = type_
if activation is not UNSET:
field_dict["activation"] = activation
if context is not UNSET:
field_dict["context"] = context
if event_date is not UNSET:
field_dict["event_date"] = event_date
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
d = dict(src_dict)
text = d.pop("text")
def _parse_id(data: object) -> None | str | Unset:
if data is None:
return data
if isinstance(data, Unset):
return data
return cast(None | str | Unset, data)
id = _parse_id(d.pop("id", UNSET))
def _parse_type_(data: object) -> None | str | Unset:
if data is None:
return data
if isinstance(data, Unset):
return data
return cast(None | str | Unset, data)
type_ = _parse_type_(d.pop("type", UNSET))
def _parse_activation(data: object) -> float | None | Unset:
if data is None:
return data
if isinstance(data, Unset):
return data
return cast(float | None | Unset, data)
activation = _parse_activation(d.pop("activation", UNSET))
def _parse_context(data: object) -> None | str | Unset:
if data is None:
return data
if isinstance(data, Unset):
return data
return cast(None | str | Unset, data)
context = _parse_context(d.pop("context", UNSET))
def _parse_event_date(data: object) -> None | str | Unset:
if data is None:
return data
if isinstance(data, Unset):
return data
return cast(None | str | Unset, data)
event_date = _parse_event_date(d.pop("event_date", UNSET))
think_fact = cls(
text=text,
id=id,
type_=type_,
activation=activation,
context=context,
event_date=event_date,
)
think_fact.additional_properties = d
return think_fact
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View file

@ -1,97 +0,0 @@
from __future__ import annotations
from collections.abc import Mapping
from typing import Any, TypeVar, cast
from attrs import define as _attrs_define
from attrs import field as _attrs_field
from ..types import UNSET, Unset
T = TypeVar("T", bound="ThinkRequest")
@_attrs_define
class ThinkRequest:
"""Request model for think endpoint.
Example:
{'context': 'This is for a research paper on AI ethics', 'query': 'What do you think about artificial
intelligence?', 'thinking_budget': 50}
Attributes:
query (str):
thinking_budget (int | Unset): Default: 50.
context (None | str | Unset):
"""
query: str
thinking_budget: int | Unset = 50
context: None | str | Unset = UNSET
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
query = self.query
thinking_budget = self.thinking_budget
context: None | str | Unset
if isinstance(self.context, Unset):
context = UNSET
else:
context = self.context
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"query": query,
}
)
if thinking_budget is not UNSET:
field_dict["thinking_budget"] = thinking_budget
if context is not UNSET:
field_dict["context"] = context
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
d = dict(src_dict)
query = d.pop("query")
thinking_budget = d.pop("thinking_budget", UNSET)
def _parse_context(data: object) -> None | str | Unset:
if data is None:
return data
if isinstance(data, Unset):
return data
return cast(None | str | Unset, data)
context = _parse_context(d.pop("context", UNSET))
think_request = cls(
query=query,
thinking_budget=thinking_budget,
context=context,
)
think_request.additional_properties = d
return think_request
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View file

@ -1,108 +0,0 @@
from __future__ import annotations
from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, TypeVar, cast
from attrs import define as _attrs_define
from attrs import field as _attrs_field
from ..types import UNSET, Unset
if TYPE_CHECKING:
from ..models.think_fact import ThinkFact
T = TypeVar("T", bound="ThinkResponse")
@_attrs_define
class ThinkResponse:
"""Response model for think endpoint.
Example:
{'based_on': [{'activation': 0.9, 'id': '123', 'text': 'AI is used in healthcare', 'type': 'world'},
{'activation': 0.85, 'id': '456', 'text': 'I discussed AI applications last week', 'type': 'agent'}],
'new_opinions': ['AI has great potential when used responsibly'], 'text': 'Based on my understanding, AI is a
transformative technology...'}
Attributes:
text (str):
based_on (list[ThinkFact] | Unset):
new_opinions (list[str] | Unset):
"""
text: str
based_on: list[ThinkFact] | Unset = UNSET
new_opinions: list[str] | Unset = UNSET
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
text = self.text
based_on: list[dict[str, Any]] | Unset = UNSET
if not isinstance(self.based_on, Unset):
based_on = []
for based_on_item_data in self.based_on:
based_on_item = based_on_item_data.to_dict()
based_on.append(based_on_item)
new_opinions: list[str] | Unset = UNSET
if not isinstance(self.new_opinions, Unset):
new_opinions = self.new_opinions
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"text": text,
}
)
if based_on is not UNSET:
field_dict["based_on"] = based_on
if new_opinions is not UNSET:
field_dict["new_opinions"] = new_opinions
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
from ..models.think_fact import ThinkFact
d = dict(src_dict)
text = d.pop("text")
_based_on = d.pop("based_on", UNSET)
based_on: list[ThinkFact] | Unset = UNSET
if _based_on is not UNSET:
based_on = []
for based_on_item_data in _based_on:
based_on_item = ThinkFact.from_dict(based_on_item_data)
based_on.append(based_on_item)
new_opinions = cast(list[str], d.pop("new_opinions", UNSET))
think_response = cls(
text=text,
based_on=based_on,
new_opinions=new_opinions,
)
think_response.additional_properties = d
return think_response
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View file

@ -1,69 +0,0 @@
from __future__ import annotations
from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, TypeVar
from attrs import define as _attrs_define
from attrs import field as _attrs_field
if TYPE_CHECKING:
from ..models.personality_traits import PersonalityTraits
T = TypeVar("T", bound="UpdatePersonalityRequest")
@_attrs_define
class UpdatePersonalityRequest:
"""Request model for updating personality traits.
Attributes:
personality (PersonalityTraits): Personality traits based on Big Five model. Example: {'agreeableness': 0.7,
'bias_strength': 0.7, 'conscientiousness': 0.6, 'extraversion': 0.5, 'neuroticism': 0.3, 'openness': 0.8}.
"""
personality: PersonalityTraits
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
personality = self.personality.to_dict()
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"personality": personality,
}
)
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
from ..models.personality_traits import PersonalityTraits
d = dict(src_dict)
personality = PersonalityTraits.from_dict(d.pop("personality"))
update_personality_request = cls(
personality=personality,
)
update_personality_request.additional_properties = d
return update_personality_request
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View file

@ -1,90 +0,0 @@
from __future__ import annotations
from collections.abc import Mapping
from typing import Any, TypeVar, cast
from attrs import define as _attrs_define
from attrs import field as _attrs_field
T = TypeVar("T", bound="ValidationError")
@_attrs_define
class ValidationError:
"""
Attributes:
loc (list[int | str]):
msg (str):
type_ (str):
"""
loc: list[int | str]
msg: str
type_: str
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
loc = []
for loc_item_data in self.loc:
loc_item: int | str
loc_item = loc_item_data
loc.append(loc_item)
msg = self.msg
type_ = self.type_
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"loc": loc,
"msg": msg,
"type": type_,
}
)
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
d = dict(src_dict)
loc = []
_loc = d.pop("loc")
for loc_item_data in _loc:
def _parse_loc_item(data: object) -> int | str:
return cast(int | str, data)
loc_item = _parse_loc_item(loc_item_data)
loc.append(loc_item)
msg = d.pop("msg")
type_ = d.pop("type")
validation_error = cls(
loc=loc,
msg=msg,
type_=type_,
)
validation_error.additional_properties = d
return validation_error
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View file

@ -1,54 +0,0 @@
"""Contains some shared types for properties"""
from collections.abc import Mapping, MutableMapping
from http import HTTPStatus
from typing import IO, BinaryIO, Generic, Literal, TypeVar
from attrs import define
class Unset:
def __bool__(self) -> Literal[False]:
return False
UNSET: Unset = Unset()
# The types that `httpx.Client(files=)` can accept, copied from that library.
FileContent = IO[bytes] | bytes | str
FileTypes = (
# (filename, file (or bytes), content_type)
tuple[str | None, FileContent, str | None]
# (filename, file (or bytes), content_type, headers)
| tuple[str | None, FileContent, str | None, Mapping[str, str]]
)
RequestFiles = list[tuple[str, FileTypes]]
@define
class File:
"""Contains information for file uploads"""
payload: BinaryIO
file_name: str | None = None
mime_type: str | None = None
def to_tuple(self) -> FileTypes:
"""Return a tuple representation that httpx will accept for multipart/form-data"""
return self.file_name, self.payload, self.mime_type
T = TypeVar("T")
@define
class Response(Generic[T]):
"""A response from an endpoint"""
status_code: HTTPStatus
content: bytes
headers: MutableMapping[str, str]
parsed: T | None
__all__ = ["UNSET", "File", "FileTypes", "RequestFiles", "Response", "Unset"]

View file

@ -0,0 +1,26 @@
"""
Memora Client - Clean, pythonic wrapper for the Memora API.
This package provides a high-level interface for common Memora operations.
For advanced use cases, use the auto-generated API client directly.
Example:
```python
from memora_client import Memora
client = Memora(base_url="http://localhost:8000")
# Store a memory
client.put(agent_id="alice", content="Alice loves AI")
# Search memories
results = client.search(agent_id="alice", query="What does Alice like?")
# Generate contextual answer
answer = client.think(agent_id="alice", query="What are my interests?")
```
"""
from .memora_client import Memora
__all__ = ["Memora"]

View file

@ -0,0 +1,283 @@
"""
Clean, pythonic wrapper for the Memora API client.
This file is MAINTAINED and NOT auto-generated. It provides a high-level,
easy-to-use interface on top of the auto-generated OpenAPI client.
"""
import asyncio
from typing import Optional, List, Dict, Any
from datetime import datetime
import memora_client_api
from memora_client_api.api import memory_operations_api, reasoning_api, agent_management_api
from memora_client_api.models import (
search_request,
batch_put_request,
memory_item,
think_request,
)
def _run_async(coro):
"""Run an async coroutine synchronously."""
try:
loop = asyncio.get_event_loop()
except RuntimeError:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
return loop.run_until_complete(coro)
class Memora:
"""
High-level, easy-to-use Memora API client.
Example:
```python
from memora_client import Memora
client = Memora(base_url="http://localhost:8000")
# Store a memory
client.put(agent_id="alice", content="Alice loves AI")
# Search memories
results = client.search(agent_id="alice", query="What does Alice like?")
# Generate contextual answer
answer = client.think(agent_id="alice", query="What are my interests?")
```
"""
def __init__(self, base_url: str, timeout: float = 30.0):
"""
Initialize the Memora client.
Args:
base_url: The base URL of the Memora API server
timeout: Request timeout in seconds (default: 30.0)
"""
config = memora_client_api.Configuration(host=base_url)
self._api_client = memora_client_api.ApiClient(config)
self._memory_api = memory_operations_api.MemoryOperationsApi(self._api_client)
self._reasoning_api = reasoning_api.ReasoningApi(self._api_client)
self._agent_api = agent_management_api.AgentManagementApi(self._api_client)
def __enter__(self):
"""Context manager entry."""
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""Context manager exit."""
self.close()
def close(self):
"""Close the API client."""
if self._api_client:
_run_async(self._api_client.close())
# Simplified methods for main operations
def put(
self,
agent_id: str,
content: str,
event_date: Optional[datetime] = None,
context: Optional[str] = None,
document_id: Optional[str] = None,
) -> Dict[str, Any]:
"""
Store a single memory (simplified interface).
Args:
agent_id: The agent ID
content: Memory content
event_date: Optional event timestamp
context: Optional context description
document_id: Optional document ID for grouping
Returns:
Response with success status
"""
return self.put_batch(
agent_id=agent_id,
items=[{"content": content, "event_date": event_date, "context": context}],
document_id=document_id,
)
def put_batch(
self,
agent_id: str,
items: List[Dict[str, Any]],
document_id: Optional[str] = None,
) -> Dict[str, Any]:
"""
Store multiple memories in batch.
Args:
agent_id: The agent ID
items: List of memory items with 'content' and optional 'event_date', 'context'
document_id: Optional document ID for grouping memories
Returns:
Response with success status and item count
"""
memory_items = [
memory_item.MemoryItem(
content=item["content"],
event_date=item.get("event_date"),
context=item.get("context"),
)
for item in items
]
request_obj = batch_put_request.BatchPutRequest(
items=memory_items,
document_id=document_id,
)
response = _run_async(self._memory_api.batch_put_memories(agent_id, request_obj))
return response.to_dict() if hasattr(response, 'to_dict') else response
def search(
self,
agent_id: str,
query: str,
fact_type: Optional[List[str]] = None,
max_tokens: int = 4096,
thinking_budget: int = 100,
) -> List[Dict[str, Any]]:
"""
Search memories using semantic similarity.
Args:
agent_id: The agent ID
query: Search query
fact_type: Optional list of fact types to filter (world, agent, opinion)
max_tokens: Maximum tokens in results (default: 4096)
thinking_budget: Token budget for search (default: 100)
Returns:
List of search results
"""
request_obj = search_request.SearchRequest(
query=query,
fact_type=fact_type,
thinking_budget=thinking_budget,
max_tokens=max_tokens,
trace=False,
)
response = _run_async(self._memory_api.search_memories(agent_id, request_obj))
if hasattr(response, 'results'):
return [r.to_dict() if hasattr(r, 'to_dict') else r for r in response.results]
return []
def think(
self,
agent_id: str,
query: str,
thinking_budget: int = 50,
context: Optional[str] = None,
) -> Dict[str, Any]:
"""
Generate a contextual answer based on agent identity and memories.
Args:
agent_id: The agent ID
query: The question or prompt
thinking_budget: Token budget for thinking (default: 50)
context: Optional additional context
Returns:
Response with answer text, facts used, and new opinions
"""
request_obj = think_request.ThinkRequest(
query=query,
thinking_budget=thinking_budget,
context=context,
)
response = _run_async(self._reasoning_api.think(agent_id, request_obj))
return response.to_dict() if hasattr(response, 'to_dict') else response
# Full-featured methods (expose more options)
def search_memories(
self,
agent_id: str,
query: str,
fact_type: Optional[List[str]] = None,
thinking_budget: int = 100,
max_tokens: int = 4096,
trace: bool = False,
question_date: Optional[str] = None,
) -> Dict[str, Any]:
"""
Search memories with all options (full-featured).
Args:
agent_id: The agent ID
query: Search query
fact_type: Optional list of fact types to filter
thinking_budget: Token budget for thinking
max_tokens: Maximum tokens in results
trace: Enable trace output
question_date: Optional ISO format date string
Returns:
Full search response with results and optional trace
"""
request_obj = search_request.SearchRequest(
query=query,
fact_type=fact_type,
thinking_budget=thinking_budget,
max_tokens=max_tokens,
trace=trace,
question_date=question_date,
)
response = _run_async(self._memory_api.search_memories(agent_id, request_obj))
return response.to_dict() if hasattr(response, 'to_dict') else response
def list_memories(
self,
agent_id: str,
fact_type: Optional[str] = None,
search_query: Optional[str] = None,
limit: int = 100,
offset: int = 0,
) -> Dict[str, Any]:
"""List memory units with pagination."""
response = _run_async(self._memory_api.list_memories(
agent_id=agent_id,
fact_type=fact_type,
q=search_query,
limit=limit,
offset=offset,
))
return response.to_dict() if hasattr(response, 'to_dict') else response
def create_agent(
self,
agent_id: str,
name: Optional[str] = None,
background: Optional[str] = None,
) -> Dict[str, Any]:
"""Create or update an agent."""
from memora_client_api.models import create_agent_request
request_obj = create_agent_request.CreateAgentRequest(
name=name,
background=background,
)
response = _run_async(self._agent_api.create_or_update_agent(agent_id, request_obj))
return response.to_dict() if hasattr(response, 'to_dict') else response
# Alias for backward compatibility
MemoraClient = Memora

View file

@ -0,0 +1,108 @@
# coding: utf-8
# flake8: noqa
"""
Agent Memory API
A temporal-semantic memory system for AI agents that stores, retrieves, and reasons over memories. ## Features * **Batch Memory Storage**: Store multiple memories efficiently with automatic fact extraction * **Semantic Search**: Find relevant memories using natural language queries * **Fact Type Filtering**: Search across world facts, agent actions, and opinions separately * **Think Endpoint**: Generate contextual answers based on agent identity and memories * **Graph Visualization**: Interactive memory graph visualization * **Document Tracking**: Track and manage memory documents with upsert support ## Architecture The system uses: - **Temporal Links**: Connect memories that are close in time - **Semantic Links**: Connect semantically similar memories - **Entity Links**: Connect memories that mention the same entities - **Spreading Activation**: Intelligent traversal for memory retrieval
The version of the OpenAPI document: 1.0.0
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
__version__ = "0.0.7"
# Define package exports
__all__ = [
"AgentManagementApi",
"DocumentsApi",
"MemoryOperationsApi",
"ReasoningApi",
"VisualizationApi",
"ApiResponse",
"ApiClient",
"Configuration",
"OpenApiException",
"ApiTypeError",
"ApiValueError",
"ApiKeyError",
"ApiAttributeError",
"ApiException",
"AddBackgroundRequest",
"AgentListItem",
"AgentListResponse",
"AgentProfileResponse",
"BackgroundResponse",
"BatchPutAsyncResponse",
"BatchPutRequest",
"BatchPutResponse",
"CreateAgentRequest",
"DeleteResponse",
"DocumentResponse",
"GraphDataResponse",
"HTTPValidationError",
"ListDocumentsResponse",
"ListMemoryUnitsResponse",
"MemoryItem",
"PersonalityTraits",
"SearchRequest",
"SearchResponse",
"SearchResult",
"ThinkFact",
"ThinkRequest",
"ThinkResponse",
"UpdatePersonalityRequest",
"ValidationError",
"ValidationErrorLocInner",
]
# import apis into sdk package
from memora_client_api.api.agent_management_api import AgentManagementApi as AgentManagementApi
from memora_client_api.api.documents_api import DocumentsApi as DocumentsApi
from memora_client_api.api.memory_operations_api import MemoryOperationsApi as MemoryOperationsApi
from memora_client_api.api.reasoning_api import ReasoningApi as ReasoningApi
from memora_client_api.api.visualization_api import VisualizationApi as VisualizationApi
# import ApiClient
from memora_client_api.api_response import ApiResponse as ApiResponse
from memora_client_api.api_client import ApiClient as ApiClient
from memora_client_api.configuration import Configuration as Configuration
from memora_client_api.exceptions import OpenApiException as OpenApiException
from memora_client_api.exceptions import ApiTypeError as ApiTypeError
from memora_client_api.exceptions import ApiValueError as ApiValueError
from memora_client_api.exceptions import ApiKeyError as ApiKeyError
from memora_client_api.exceptions import ApiAttributeError as ApiAttributeError
from memora_client_api.exceptions import ApiException as ApiException
# import models into sdk package
from memora_client_api.models.add_background_request import AddBackgroundRequest as AddBackgroundRequest
from memora_client_api.models.agent_list_item import AgentListItem as AgentListItem
from memora_client_api.models.agent_list_response import AgentListResponse as AgentListResponse
from memora_client_api.models.agent_profile_response import AgentProfileResponse as AgentProfileResponse
from memora_client_api.models.background_response import BackgroundResponse as BackgroundResponse
from memora_client_api.models.batch_put_async_response import BatchPutAsyncResponse as BatchPutAsyncResponse
from memora_client_api.models.batch_put_request import BatchPutRequest as BatchPutRequest
from memora_client_api.models.batch_put_response import BatchPutResponse as BatchPutResponse
from memora_client_api.models.create_agent_request import CreateAgentRequest as CreateAgentRequest
from memora_client_api.models.delete_response import DeleteResponse as DeleteResponse
from memora_client_api.models.document_response import DocumentResponse as DocumentResponse
from memora_client_api.models.graph_data_response import GraphDataResponse as GraphDataResponse
from memora_client_api.models.http_validation_error import HTTPValidationError as HTTPValidationError
from memora_client_api.models.list_documents_response import ListDocumentsResponse as ListDocumentsResponse
from memora_client_api.models.list_memory_units_response import ListMemoryUnitsResponse as ListMemoryUnitsResponse
from memora_client_api.models.memory_item import MemoryItem as MemoryItem
from memora_client_api.models.personality_traits import PersonalityTraits as PersonalityTraits
from memora_client_api.models.search_request import SearchRequest as SearchRequest
from memora_client_api.models.search_response import SearchResponse as SearchResponse
from memora_client_api.models.search_result import SearchResult as SearchResult
from memora_client_api.models.think_fact import ThinkFact as ThinkFact
from memora_client_api.models.think_request import ThinkRequest as ThinkRequest
from memora_client_api.models.think_response import ThinkResponse as ThinkResponse
from memora_client_api.models.update_personality_request import UpdatePersonalityRequest as UpdatePersonalityRequest
from memora_client_api.models.validation_error import ValidationError as ValidationError
from memora_client_api.models.validation_error_loc_inner import ValidationErrorLocInner as ValidationErrorLocInner

View file

@ -0,0 +1,9 @@
# flake8: noqa
# import apis into api package
from memora_client_api.api.agent_management_api import AgentManagementApi
from memora_client_api.api.documents_api import DocumentsApi
from memora_client_api.api.memory_operations_api import MemoryOperationsApi
from memora_client_api.api.reasoning_api import ReasoningApi
from memora_client_api.api.visualization_api import VisualizationApi

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,909 @@
# coding: utf-8
"""
Agent Memory API
A temporal-semantic memory system for AI agents that stores, retrieves, and reasons over memories. ## Features * **Batch Memory Storage**: Store multiple memories efficiently with automatic fact extraction * **Semantic Search**: Find relevant memories using natural language queries * **Fact Type Filtering**: Search across world facts, agent actions, and opinions separately * **Think Endpoint**: Generate contextual answers based on agent identity and memories * **Graph Visualization**: Interactive memory graph visualization * **Document Tracking**: Track and manage memory documents with upsert support ## Architecture The system uses: - **Temporal Links**: Connect memories that are close in time - **Semantic Links**: Connect semantically similar memories - **Entity Links**: Connect memories that mention the same entities - **Spreading Activation**: Intelligent traversal for memory retrieval
The version of the OpenAPI document: 1.0.0
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import warnings
from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt
from typing import Any, Dict, List, Optional, Tuple, Union
from typing_extensions import Annotated
from pydantic import StrictInt, StrictStr
from typing import Any, Optional
from memora_client_api.models.document_response import DocumentResponse
from memora_client_api.models.list_documents_response import ListDocumentsResponse
from memora_client_api.api_client import ApiClient, RequestSerialized
from memora_client_api.api_response import ApiResponse
from memora_client_api.rest import RESTResponseType
class DocumentsApi:
"""NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
def __init__(self, api_client=None) -> None:
if api_client is None:
api_client = ApiClient.get_default()
self.api_client = api_client
@validate_call
async def delete_document(
self,
agent_id: StrictStr,
document_id: StrictStr,
_request_timeout: Union[
None,
Annotated[StrictFloat, Field(gt=0)],
Tuple[
Annotated[StrictFloat, Field(gt=0)],
Annotated[StrictFloat, Field(gt=0)]
]
] = None,
_request_auth: Optional[Dict[StrictStr, Any]] = None,
_content_type: Optional[StrictStr] = None,
_headers: Optional[Dict[StrictStr, Any]] = None,
_host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,
) -> object:
"""Delete a document
Delete a document and all its associated memory units and links. This will cascade delete: - The document itself - All memory units extracted from this document - All links (temporal, semantic, entity) associated with those memory units This operation cannot be undone.
:param agent_id: (required)
:type agent_id: str
:param document_id: (required)
:type document_id: str
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:type _request_timeout: int, tuple(int, int), optional
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the
authentication in the spec for a single request.
:type _request_auth: dict, optional
:param _content_type: force content-type for the request.
:type _content_type: str, Optional
:param _headers: set to override the headers for a single
request; this effectively ignores the headers
in the spec for a single request.
:type _headers: dict, optional
:param _host_index: set to override the host_index for a single
request; this effectively ignores the host_index
in the spec for a single request.
:type _host_index: int, optional
:return: Returns the result object.
""" # noqa: E501
_param = self._delete_document_serialize(
agent_id=agent_id,
document_id=document_id,
_request_auth=_request_auth,
_content_type=_content_type,
_headers=_headers,
_host_index=_host_index
)
_response_types_map: Dict[str, Optional[str]] = {
'200': "object",
'422': "HTTPValidationError",
}
response_data = await self.api_client.call_api(
*_param,
_request_timeout=_request_timeout
)
await response_data.read()
return self.api_client.response_deserialize(
response_data=response_data,
response_types_map=_response_types_map,
).data
@validate_call
async def delete_document_with_http_info(
self,
agent_id: StrictStr,
document_id: StrictStr,
_request_timeout: Union[
None,
Annotated[StrictFloat, Field(gt=0)],
Tuple[
Annotated[StrictFloat, Field(gt=0)],
Annotated[StrictFloat, Field(gt=0)]
]
] = None,
_request_auth: Optional[Dict[StrictStr, Any]] = None,
_content_type: Optional[StrictStr] = None,
_headers: Optional[Dict[StrictStr, Any]] = None,
_host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,
) -> ApiResponse[object]:
"""Delete a document
Delete a document and all its associated memory units and links. This will cascade delete: - The document itself - All memory units extracted from this document - All links (temporal, semantic, entity) associated with those memory units This operation cannot be undone.
:param agent_id: (required)
:type agent_id: str
:param document_id: (required)
:type document_id: str
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:type _request_timeout: int, tuple(int, int), optional
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the
authentication in the spec for a single request.
:type _request_auth: dict, optional
:param _content_type: force content-type for the request.
:type _content_type: str, Optional
:param _headers: set to override the headers for a single
request; this effectively ignores the headers
in the spec for a single request.
:type _headers: dict, optional
:param _host_index: set to override the host_index for a single
request; this effectively ignores the host_index
in the spec for a single request.
:type _host_index: int, optional
:return: Returns the result object.
""" # noqa: E501
_param = self._delete_document_serialize(
agent_id=agent_id,
document_id=document_id,
_request_auth=_request_auth,
_content_type=_content_type,
_headers=_headers,
_host_index=_host_index
)
_response_types_map: Dict[str, Optional[str]] = {
'200': "object",
'422': "HTTPValidationError",
}
response_data = await self.api_client.call_api(
*_param,
_request_timeout=_request_timeout
)
await response_data.read()
return self.api_client.response_deserialize(
response_data=response_data,
response_types_map=_response_types_map,
)
@validate_call
async def delete_document_without_preload_content(
self,
agent_id: StrictStr,
document_id: StrictStr,
_request_timeout: Union[
None,
Annotated[StrictFloat, Field(gt=0)],
Tuple[
Annotated[StrictFloat, Field(gt=0)],
Annotated[StrictFloat, Field(gt=0)]
]
] = None,
_request_auth: Optional[Dict[StrictStr, Any]] = None,
_content_type: Optional[StrictStr] = None,
_headers: Optional[Dict[StrictStr, Any]] = None,
_host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,
) -> RESTResponseType:
"""Delete a document
Delete a document and all its associated memory units and links. This will cascade delete: - The document itself - All memory units extracted from this document - All links (temporal, semantic, entity) associated with those memory units This operation cannot be undone.
:param agent_id: (required)
:type agent_id: str
:param document_id: (required)
:type document_id: str
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:type _request_timeout: int, tuple(int, int), optional
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the
authentication in the spec for a single request.
:type _request_auth: dict, optional
:param _content_type: force content-type for the request.
:type _content_type: str, Optional
:param _headers: set to override the headers for a single
request; this effectively ignores the headers
in the spec for a single request.
:type _headers: dict, optional
:param _host_index: set to override the host_index for a single
request; this effectively ignores the host_index
in the spec for a single request.
:type _host_index: int, optional
:return: Returns the result object.
""" # noqa: E501
_param = self._delete_document_serialize(
agent_id=agent_id,
document_id=document_id,
_request_auth=_request_auth,
_content_type=_content_type,
_headers=_headers,
_host_index=_host_index
)
_response_types_map: Dict[str, Optional[str]] = {
'200': "object",
'422': "HTTPValidationError",
}
response_data = await self.api_client.call_api(
*_param,
_request_timeout=_request_timeout
)
return response_data.response
def _delete_document_serialize(
self,
agent_id,
document_id,
_request_auth,
_content_type,
_headers,
_host_index,
) -> RequestSerialized:
_host = None
_collection_formats: Dict[str, str] = {
}
_path_params: Dict[str, str] = {}
_query_params: List[Tuple[str, str]] = []
_header_params: Dict[str, Optional[str]] = _headers or {}
_form_params: List[Tuple[str, str]] = []
_files: Dict[
str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]]
] = {}
_body_params: Optional[bytes] = None
# process the path parameters
if agent_id is not None:
_path_params['agent_id'] = agent_id
if document_id is not None:
_path_params['document_id'] = document_id
# process the query parameters
# process the header parameters
# process the form parameters
# process the body parameter
# set the HTTP header `Accept`
if 'Accept' not in _header_params:
_header_params['Accept'] = self.api_client.select_header_accept(
[
'application/json'
]
)
# authentication setting
_auth_settings: List[str] = [
]
return self.api_client.param_serialize(
method='DELETE',
resource_path='/api/v1/agents/{agent_id}/documents/{document_id}',
path_params=_path_params,
query_params=_query_params,
header_params=_header_params,
body=_body_params,
post_params=_form_params,
files=_files,
auth_settings=_auth_settings,
collection_formats=_collection_formats,
_host=_host,
_request_auth=_request_auth
)
@validate_call
async def get_document(
self,
agent_id: StrictStr,
document_id: StrictStr,
_request_timeout: Union[
None,
Annotated[StrictFloat, Field(gt=0)],
Tuple[
Annotated[StrictFloat, Field(gt=0)],
Annotated[StrictFloat, Field(gt=0)]
]
] = None,
_request_auth: Optional[Dict[StrictStr, Any]] = None,
_content_type: Optional[StrictStr] = None,
_headers: Optional[Dict[StrictStr, Any]] = None,
_host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,
) -> DocumentResponse:
"""Get document details
Get a specific document including its original text
:param agent_id: (required)
:type agent_id: str
:param document_id: (required)
:type document_id: str
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:type _request_timeout: int, tuple(int, int), optional
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the
authentication in the spec for a single request.
:type _request_auth: dict, optional
:param _content_type: force content-type for the request.
:type _content_type: str, Optional
:param _headers: set to override the headers for a single
request; this effectively ignores the headers
in the spec for a single request.
:type _headers: dict, optional
:param _host_index: set to override the host_index for a single
request; this effectively ignores the host_index
in the spec for a single request.
:type _host_index: int, optional
:return: Returns the result object.
""" # noqa: E501
_param = self._get_document_serialize(
agent_id=agent_id,
document_id=document_id,
_request_auth=_request_auth,
_content_type=_content_type,
_headers=_headers,
_host_index=_host_index
)
_response_types_map: Dict[str, Optional[str]] = {
'200': "DocumentResponse",
'422': "HTTPValidationError",
}
response_data = await self.api_client.call_api(
*_param,
_request_timeout=_request_timeout
)
await response_data.read()
return self.api_client.response_deserialize(
response_data=response_data,
response_types_map=_response_types_map,
).data
@validate_call
async def get_document_with_http_info(
self,
agent_id: StrictStr,
document_id: StrictStr,
_request_timeout: Union[
None,
Annotated[StrictFloat, Field(gt=0)],
Tuple[
Annotated[StrictFloat, Field(gt=0)],
Annotated[StrictFloat, Field(gt=0)]
]
] = None,
_request_auth: Optional[Dict[StrictStr, Any]] = None,
_content_type: Optional[StrictStr] = None,
_headers: Optional[Dict[StrictStr, Any]] = None,
_host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,
) -> ApiResponse[DocumentResponse]:
"""Get document details
Get a specific document including its original text
:param agent_id: (required)
:type agent_id: str
:param document_id: (required)
:type document_id: str
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:type _request_timeout: int, tuple(int, int), optional
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the
authentication in the spec for a single request.
:type _request_auth: dict, optional
:param _content_type: force content-type for the request.
:type _content_type: str, Optional
:param _headers: set to override the headers for a single
request; this effectively ignores the headers
in the spec for a single request.
:type _headers: dict, optional
:param _host_index: set to override the host_index for a single
request; this effectively ignores the host_index
in the spec for a single request.
:type _host_index: int, optional
:return: Returns the result object.
""" # noqa: E501
_param = self._get_document_serialize(
agent_id=agent_id,
document_id=document_id,
_request_auth=_request_auth,
_content_type=_content_type,
_headers=_headers,
_host_index=_host_index
)
_response_types_map: Dict[str, Optional[str]] = {
'200': "DocumentResponse",
'422': "HTTPValidationError",
}
response_data = await self.api_client.call_api(
*_param,
_request_timeout=_request_timeout
)
await response_data.read()
return self.api_client.response_deserialize(
response_data=response_data,
response_types_map=_response_types_map,
)
@validate_call
async def get_document_without_preload_content(
self,
agent_id: StrictStr,
document_id: StrictStr,
_request_timeout: Union[
None,
Annotated[StrictFloat, Field(gt=0)],
Tuple[
Annotated[StrictFloat, Field(gt=0)],
Annotated[StrictFloat, Field(gt=0)]
]
] = None,
_request_auth: Optional[Dict[StrictStr, Any]] = None,
_content_type: Optional[StrictStr] = None,
_headers: Optional[Dict[StrictStr, Any]] = None,
_host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,
) -> RESTResponseType:
"""Get document details
Get a specific document including its original text
:param agent_id: (required)
:type agent_id: str
:param document_id: (required)
:type document_id: str
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:type _request_timeout: int, tuple(int, int), optional
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the
authentication in the spec for a single request.
:type _request_auth: dict, optional
:param _content_type: force content-type for the request.
:type _content_type: str, Optional
:param _headers: set to override the headers for a single
request; this effectively ignores the headers
in the spec for a single request.
:type _headers: dict, optional
:param _host_index: set to override the host_index for a single
request; this effectively ignores the host_index
in the spec for a single request.
:type _host_index: int, optional
:return: Returns the result object.
""" # noqa: E501
_param = self._get_document_serialize(
agent_id=agent_id,
document_id=document_id,
_request_auth=_request_auth,
_content_type=_content_type,
_headers=_headers,
_host_index=_host_index
)
_response_types_map: Dict[str, Optional[str]] = {
'200': "DocumentResponse",
'422': "HTTPValidationError",
}
response_data = await self.api_client.call_api(
*_param,
_request_timeout=_request_timeout
)
return response_data.response
def _get_document_serialize(
self,
agent_id,
document_id,
_request_auth,
_content_type,
_headers,
_host_index,
) -> RequestSerialized:
_host = None
_collection_formats: Dict[str, str] = {
}
_path_params: Dict[str, str] = {}
_query_params: List[Tuple[str, str]] = []
_header_params: Dict[str, Optional[str]] = _headers or {}
_form_params: List[Tuple[str, str]] = []
_files: Dict[
str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]]
] = {}
_body_params: Optional[bytes] = None
# process the path parameters
if agent_id is not None:
_path_params['agent_id'] = agent_id
if document_id is not None:
_path_params['document_id'] = document_id
# process the query parameters
# process the header parameters
# process the form parameters
# process the body parameter
# set the HTTP header `Accept`
if 'Accept' not in _header_params:
_header_params['Accept'] = self.api_client.select_header_accept(
[
'application/json'
]
)
# authentication setting
_auth_settings: List[str] = [
]
return self.api_client.param_serialize(
method='GET',
resource_path='/api/v1/agents/{agent_id}/documents/{document_id}',
path_params=_path_params,
query_params=_query_params,
header_params=_header_params,
body=_body_params,
post_params=_form_params,
files=_files,
auth_settings=_auth_settings,
collection_formats=_collection_formats,
_host=_host,
_request_auth=_request_auth
)
@validate_call
async def list_documents(
self,
agent_id: StrictStr,
q: Optional[StrictStr] = None,
limit: Optional[StrictInt] = None,
offset: Optional[StrictInt] = None,
_request_timeout: Union[
None,
Annotated[StrictFloat, Field(gt=0)],
Tuple[
Annotated[StrictFloat, Field(gt=0)],
Annotated[StrictFloat, Field(gt=0)]
]
] = None,
_request_auth: Optional[Dict[StrictStr, Any]] = None,
_content_type: Optional[StrictStr] = None,
_headers: Optional[Dict[StrictStr, Any]] = None,
_host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,
) -> ListDocumentsResponse:
"""List documents
List documents with pagination and optional search. Documents are the source content from which memory units are extracted.
:param agent_id: (required)
:type agent_id: str
:param q:
:type q: str
:param limit:
:type limit: int
:param offset:
:type offset: int
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:type _request_timeout: int, tuple(int, int), optional
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the
authentication in the spec for a single request.
:type _request_auth: dict, optional
:param _content_type: force content-type for the request.
:type _content_type: str, Optional
:param _headers: set to override the headers for a single
request; this effectively ignores the headers
in the spec for a single request.
:type _headers: dict, optional
:param _host_index: set to override the host_index for a single
request; this effectively ignores the host_index
in the spec for a single request.
:type _host_index: int, optional
:return: Returns the result object.
""" # noqa: E501
_param = self._list_documents_serialize(
agent_id=agent_id,
q=q,
limit=limit,
offset=offset,
_request_auth=_request_auth,
_content_type=_content_type,
_headers=_headers,
_host_index=_host_index
)
_response_types_map: Dict[str, Optional[str]] = {
'200': "ListDocumentsResponse",
'422': "HTTPValidationError",
}
response_data = await self.api_client.call_api(
*_param,
_request_timeout=_request_timeout
)
await response_data.read()
return self.api_client.response_deserialize(
response_data=response_data,
response_types_map=_response_types_map,
).data
@validate_call
async def list_documents_with_http_info(
self,
agent_id: StrictStr,
q: Optional[StrictStr] = None,
limit: Optional[StrictInt] = None,
offset: Optional[StrictInt] = None,
_request_timeout: Union[
None,
Annotated[StrictFloat, Field(gt=0)],
Tuple[
Annotated[StrictFloat, Field(gt=0)],
Annotated[StrictFloat, Field(gt=0)]
]
] = None,
_request_auth: Optional[Dict[StrictStr, Any]] = None,
_content_type: Optional[StrictStr] = None,
_headers: Optional[Dict[StrictStr, Any]] = None,
_host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,
) -> ApiResponse[ListDocumentsResponse]:
"""List documents
List documents with pagination and optional search. Documents are the source content from which memory units are extracted.
:param agent_id: (required)
:type agent_id: str
:param q:
:type q: str
:param limit:
:type limit: int
:param offset:
:type offset: int
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:type _request_timeout: int, tuple(int, int), optional
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the
authentication in the spec for a single request.
:type _request_auth: dict, optional
:param _content_type: force content-type for the request.
:type _content_type: str, Optional
:param _headers: set to override the headers for a single
request; this effectively ignores the headers
in the spec for a single request.
:type _headers: dict, optional
:param _host_index: set to override the host_index for a single
request; this effectively ignores the host_index
in the spec for a single request.
:type _host_index: int, optional
:return: Returns the result object.
""" # noqa: E501
_param = self._list_documents_serialize(
agent_id=agent_id,
q=q,
limit=limit,
offset=offset,
_request_auth=_request_auth,
_content_type=_content_type,
_headers=_headers,
_host_index=_host_index
)
_response_types_map: Dict[str, Optional[str]] = {
'200': "ListDocumentsResponse",
'422': "HTTPValidationError",
}
response_data = await self.api_client.call_api(
*_param,
_request_timeout=_request_timeout
)
await response_data.read()
return self.api_client.response_deserialize(
response_data=response_data,
response_types_map=_response_types_map,
)
@validate_call
async def list_documents_without_preload_content(
self,
agent_id: StrictStr,
q: Optional[StrictStr] = None,
limit: Optional[StrictInt] = None,
offset: Optional[StrictInt] = None,
_request_timeout: Union[
None,
Annotated[StrictFloat, Field(gt=0)],
Tuple[
Annotated[StrictFloat, Field(gt=0)],
Annotated[StrictFloat, Field(gt=0)]
]
] = None,
_request_auth: Optional[Dict[StrictStr, Any]] = None,
_content_type: Optional[StrictStr] = None,
_headers: Optional[Dict[StrictStr, Any]] = None,
_host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,
) -> RESTResponseType:
"""List documents
List documents with pagination and optional search. Documents are the source content from which memory units are extracted.
:param agent_id: (required)
:type agent_id: str
:param q:
:type q: str
:param limit:
:type limit: int
:param offset:
:type offset: int
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:type _request_timeout: int, tuple(int, int), optional
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the
authentication in the spec for a single request.
:type _request_auth: dict, optional
:param _content_type: force content-type for the request.
:type _content_type: str, Optional
:param _headers: set to override the headers for a single
request; this effectively ignores the headers
in the spec for a single request.
:type _headers: dict, optional
:param _host_index: set to override the host_index for a single
request; this effectively ignores the host_index
in the spec for a single request.
:type _host_index: int, optional
:return: Returns the result object.
""" # noqa: E501
_param = self._list_documents_serialize(
agent_id=agent_id,
q=q,
limit=limit,
offset=offset,
_request_auth=_request_auth,
_content_type=_content_type,
_headers=_headers,
_host_index=_host_index
)
_response_types_map: Dict[str, Optional[str]] = {
'200': "ListDocumentsResponse",
'422': "HTTPValidationError",
}
response_data = await self.api_client.call_api(
*_param,
_request_timeout=_request_timeout
)
return response_data.response
def _list_documents_serialize(
self,
agent_id,
q,
limit,
offset,
_request_auth,
_content_type,
_headers,
_host_index,
) -> RequestSerialized:
_host = None
_collection_formats: Dict[str, str] = {
}
_path_params: Dict[str, str] = {}
_query_params: List[Tuple[str, str]] = []
_header_params: Dict[str, Optional[str]] = _headers or {}
_form_params: List[Tuple[str, str]] = []
_files: Dict[
str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]]
] = {}
_body_params: Optional[bytes] = None
# process the path parameters
if agent_id is not None:
_path_params['agent_id'] = agent_id
# process the query parameters
if q is not None:
_query_params.append(('q', q))
if limit is not None:
_query_params.append(('limit', limit))
if offset is not None:
_query_params.append(('offset', offset))
# process the header parameters
# process the form parameters
# process the body parameter
# set the HTTP header `Accept`
if 'Accept' not in _header_params:
_header_params['Accept'] = self.api_client.select_header_accept(
[
'application/json'
]
)
# authentication setting
_auth_settings: List[str] = [
]
return self.api_client.param_serialize(
method='GET',
resource_path='/api/v1/agents/{agent_id}/documents',
path_params=_path_params,
query_params=_query_params,
header_params=_header_params,
body=_body_params,
post_params=_form_params,
files=_files,
auth_settings=_auth_settings,
collection_formats=_collection_formats,
_host=_host,
_request_auth=_request_auth
)

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,329 @@
# coding: utf-8
"""
Agent Memory API
A temporal-semantic memory system for AI agents that stores, retrieves, and reasons over memories. ## Features * **Batch Memory Storage**: Store multiple memories efficiently with automatic fact extraction * **Semantic Search**: Find relevant memories using natural language queries * **Fact Type Filtering**: Search across world facts, agent actions, and opinions separately * **Think Endpoint**: Generate contextual answers based on agent identity and memories * **Graph Visualization**: Interactive memory graph visualization * **Document Tracking**: Track and manage memory documents with upsert support ## Architecture The system uses: - **Temporal Links**: Connect memories that are close in time - **Semantic Links**: Connect semantically similar memories - **Entity Links**: Connect memories that mention the same entities - **Spreading Activation**: Intelligent traversal for memory retrieval
The version of the OpenAPI document: 1.0.0
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import warnings
from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt
from typing import Any, Dict, List, Optional, Tuple, Union
from typing_extensions import Annotated
from pydantic import StrictStr
from memora_client_api.models.think_request import ThinkRequest
from memora_client_api.models.think_response import ThinkResponse
from memora_client_api.api_client import ApiClient, RequestSerialized
from memora_client_api.api_response import ApiResponse
from memora_client_api.rest import RESTResponseType
class ReasoningApi:
"""NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
def __init__(self, api_client=None) -> None:
if api_client is None:
api_client = ApiClient.get_default()
self.api_client = api_client
@validate_call
async def think(
self,
agent_id: StrictStr,
think_request: ThinkRequest,
_request_timeout: Union[
None,
Annotated[StrictFloat, Field(gt=0)],
Tuple[
Annotated[StrictFloat, Field(gt=0)],
Annotated[StrictFloat, Field(gt=0)]
]
] = None,
_request_auth: Optional[Dict[StrictStr, Any]] = None,
_content_type: Optional[StrictStr] = None,
_headers: Optional[Dict[StrictStr, Any]] = None,
_host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,
) -> ThinkResponse:
"""Think and generate answer
Think and formulate an answer using agent identity, world facts, and opinions. This endpoint: 1. Retrieves agent facts (agent's identity) 2. Retrieves world facts relevant to the query 3. Retrieves existing opinions (agent's perspectives) 4. Uses LLM to formulate a contextual answer 5. Extracts and stores any new opinions formed 6. Returns plain text answer, the facts used, and new opinions
:param agent_id: (required)
:type agent_id: str
:param think_request: (required)
:type think_request: ThinkRequest
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:type _request_timeout: int, tuple(int, int), optional
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the
authentication in the spec for a single request.
:type _request_auth: dict, optional
:param _content_type: force content-type for the request.
:type _content_type: str, Optional
:param _headers: set to override the headers for a single
request; this effectively ignores the headers
in the spec for a single request.
:type _headers: dict, optional
:param _host_index: set to override the host_index for a single
request; this effectively ignores the host_index
in the spec for a single request.
:type _host_index: int, optional
:return: Returns the result object.
""" # noqa: E501
_param = self._think_serialize(
agent_id=agent_id,
think_request=think_request,
_request_auth=_request_auth,
_content_type=_content_type,
_headers=_headers,
_host_index=_host_index
)
_response_types_map: Dict[str, Optional[str]] = {
'200': "ThinkResponse",
'422': "HTTPValidationError",
}
response_data = await self.api_client.call_api(
*_param,
_request_timeout=_request_timeout
)
await response_data.read()
return self.api_client.response_deserialize(
response_data=response_data,
response_types_map=_response_types_map,
).data
@validate_call
async def think_with_http_info(
self,
agent_id: StrictStr,
think_request: ThinkRequest,
_request_timeout: Union[
None,
Annotated[StrictFloat, Field(gt=0)],
Tuple[
Annotated[StrictFloat, Field(gt=0)],
Annotated[StrictFloat, Field(gt=0)]
]
] = None,
_request_auth: Optional[Dict[StrictStr, Any]] = None,
_content_type: Optional[StrictStr] = None,
_headers: Optional[Dict[StrictStr, Any]] = None,
_host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,
) -> ApiResponse[ThinkResponse]:
"""Think and generate answer
Think and formulate an answer using agent identity, world facts, and opinions. This endpoint: 1. Retrieves agent facts (agent's identity) 2. Retrieves world facts relevant to the query 3. Retrieves existing opinions (agent's perspectives) 4. Uses LLM to formulate a contextual answer 5. Extracts and stores any new opinions formed 6. Returns plain text answer, the facts used, and new opinions
:param agent_id: (required)
:type agent_id: str
:param think_request: (required)
:type think_request: ThinkRequest
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:type _request_timeout: int, tuple(int, int), optional
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the
authentication in the spec for a single request.
:type _request_auth: dict, optional
:param _content_type: force content-type for the request.
:type _content_type: str, Optional
:param _headers: set to override the headers for a single
request; this effectively ignores the headers
in the spec for a single request.
:type _headers: dict, optional
:param _host_index: set to override the host_index for a single
request; this effectively ignores the host_index
in the spec for a single request.
:type _host_index: int, optional
:return: Returns the result object.
""" # noqa: E501
_param = self._think_serialize(
agent_id=agent_id,
think_request=think_request,
_request_auth=_request_auth,
_content_type=_content_type,
_headers=_headers,
_host_index=_host_index
)
_response_types_map: Dict[str, Optional[str]] = {
'200': "ThinkResponse",
'422': "HTTPValidationError",
}
response_data = await self.api_client.call_api(
*_param,
_request_timeout=_request_timeout
)
await response_data.read()
return self.api_client.response_deserialize(
response_data=response_data,
response_types_map=_response_types_map,
)
@validate_call
async def think_without_preload_content(
self,
agent_id: StrictStr,
think_request: ThinkRequest,
_request_timeout: Union[
None,
Annotated[StrictFloat, Field(gt=0)],
Tuple[
Annotated[StrictFloat, Field(gt=0)],
Annotated[StrictFloat, Field(gt=0)]
]
] = None,
_request_auth: Optional[Dict[StrictStr, Any]] = None,
_content_type: Optional[StrictStr] = None,
_headers: Optional[Dict[StrictStr, Any]] = None,
_host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,
) -> RESTResponseType:
"""Think and generate answer
Think and formulate an answer using agent identity, world facts, and opinions. This endpoint: 1. Retrieves agent facts (agent's identity) 2. Retrieves world facts relevant to the query 3. Retrieves existing opinions (agent's perspectives) 4. Uses LLM to formulate a contextual answer 5. Extracts and stores any new opinions formed 6. Returns plain text answer, the facts used, and new opinions
:param agent_id: (required)
:type agent_id: str
:param think_request: (required)
:type think_request: ThinkRequest
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:type _request_timeout: int, tuple(int, int), optional
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the
authentication in the spec for a single request.
:type _request_auth: dict, optional
:param _content_type: force content-type for the request.
:type _content_type: str, Optional
:param _headers: set to override the headers for a single
request; this effectively ignores the headers
in the spec for a single request.
:type _headers: dict, optional
:param _host_index: set to override the host_index for a single
request; this effectively ignores the host_index
in the spec for a single request.
:type _host_index: int, optional
:return: Returns the result object.
""" # noqa: E501
_param = self._think_serialize(
agent_id=agent_id,
think_request=think_request,
_request_auth=_request_auth,
_content_type=_content_type,
_headers=_headers,
_host_index=_host_index
)
_response_types_map: Dict[str, Optional[str]] = {
'200': "ThinkResponse",
'422': "HTTPValidationError",
}
response_data = await self.api_client.call_api(
*_param,
_request_timeout=_request_timeout
)
return response_data.response
def _think_serialize(
self,
agent_id,
think_request,
_request_auth,
_content_type,
_headers,
_host_index,
) -> RequestSerialized:
_host = None
_collection_formats: Dict[str, str] = {
}
_path_params: Dict[str, str] = {}
_query_params: List[Tuple[str, str]] = []
_header_params: Dict[str, Optional[str]] = _headers or {}
_form_params: List[Tuple[str, str]] = []
_files: Dict[
str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]]
] = {}
_body_params: Optional[bytes] = None
# process the path parameters
if agent_id is not None:
_path_params['agent_id'] = agent_id
# process the query parameters
# process the header parameters
# process the form parameters
# process the body parameter
if think_request is not None:
_body_params = think_request
# set the HTTP header `Accept`
if 'Accept' not in _header_params:
_header_params['Accept'] = self.api_client.select_header_accept(
[
'application/json'
]
)
# set the HTTP header `Content-Type`
if _content_type:
_header_params['Content-Type'] = _content_type
else:
_default_content_type = (
self.api_client.select_header_content_type(
[
'application/json'
]
)
)
if _default_content_type is not None:
_header_params['Content-Type'] = _default_content_type
# authentication setting
_auth_settings: List[str] = [
]
return self.api_client.param_serialize(
method='POST',
resource_path='/api/v1/agents/{agent_id}/think',
path_params=_path_params,
query_params=_query_params,
header_params=_header_params,
body=_body_params,
post_params=_form_params,
files=_files,
auth_settings=_auth_settings,
collection_formats=_collection_formats,
_host=_host,
_request_auth=_request_auth
)

View file

@ -0,0 +1,318 @@
# coding: utf-8
"""
Agent Memory API
A temporal-semantic memory system for AI agents that stores, retrieves, and reasons over memories. ## Features * **Batch Memory Storage**: Store multiple memories efficiently with automatic fact extraction * **Semantic Search**: Find relevant memories using natural language queries * **Fact Type Filtering**: Search across world facts, agent actions, and opinions separately * **Think Endpoint**: Generate contextual answers based on agent identity and memories * **Graph Visualization**: Interactive memory graph visualization * **Document Tracking**: Track and manage memory documents with upsert support ## Architecture The system uses: - **Temporal Links**: Connect memories that are close in time - **Semantic Links**: Connect semantically similar memories - **Entity Links**: Connect memories that mention the same entities - **Spreading Activation**: Intelligent traversal for memory retrieval
The version of the OpenAPI document: 1.0.0
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import warnings
from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt
from typing import Any, Dict, List, Optional, Tuple, Union
from typing_extensions import Annotated
from pydantic import StrictStr
from typing import Optional
from memora_client_api.models.graph_data_response import GraphDataResponse
from memora_client_api.api_client import ApiClient, RequestSerialized
from memora_client_api.api_response import ApiResponse
from memora_client_api.rest import RESTResponseType
class VisualizationApi:
"""NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
def __init__(self, api_client=None) -> None:
if api_client is None:
api_client = ApiClient.get_default()
self.api_client = api_client
@validate_call
async def get_graph(
self,
agent_id: StrictStr,
fact_type: Optional[StrictStr] = None,
_request_timeout: Union[
None,
Annotated[StrictFloat, Field(gt=0)],
Tuple[
Annotated[StrictFloat, Field(gt=0)],
Annotated[StrictFloat, Field(gt=0)]
]
] = None,
_request_auth: Optional[Dict[StrictStr, Any]] = None,
_content_type: Optional[StrictStr] = None,
_headers: Optional[Dict[StrictStr, Any]] = None,
_host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,
) -> GraphDataResponse:
"""Get memory graph data
Retrieve graph data for visualization, optionally filtered by fact_type (world/agent/opinion). Limited to 1000 most recent items.
:param agent_id: (required)
:type agent_id: str
:param fact_type:
:type fact_type: str
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:type _request_timeout: int, tuple(int, int), optional
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the
authentication in the spec for a single request.
:type _request_auth: dict, optional
:param _content_type: force content-type for the request.
:type _content_type: str, Optional
:param _headers: set to override the headers for a single
request; this effectively ignores the headers
in the spec for a single request.
:type _headers: dict, optional
:param _host_index: set to override the host_index for a single
request; this effectively ignores the host_index
in the spec for a single request.
:type _host_index: int, optional
:return: Returns the result object.
""" # noqa: E501
_param = self._get_graph_serialize(
agent_id=agent_id,
fact_type=fact_type,
_request_auth=_request_auth,
_content_type=_content_type,
_headers=_headers,
_host_index=_host_index
)
_response_types_map: Dict[str, Optional[str]] = {
'200': "GraphDataResponse",
'422': "HTTPValidationError",
}
response_data = await self.api_client.call_api(
*_param,
_request_timeout=_request_timeout
)
await response_data.read()
return self.api_client.response_deserialize(
response_data=response_data,
response_types_map=_response_types_map,
).data
@validate_call
async def get_graph_with_http_info(
self,
agent_id: StrictStr,
fact_type: Optional[StrictStr] = None,
_request_timeout: Union[
None,
Annotated[StrictFloat, Field(gt=0)],
Tuple[
Annotated[StrictFloat, Field(gt=0)],
Annotated[StrictFloat, Field(gt=0)]
]
] = None,
_request_auth: Optional[Dict[StrictStr, Any]] = None,
_content_type: Optional[StrictStr] = None,
_headers: Optional[Dict[StrictStr, Any]] = None,
_host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,
) -> ApiResponse[GraphDataResponse]:
"""Get memory graph data
Retrieve graph data for visualization, optionally filtered by fact_type (world/agent/opinion). Limited to 1000 most recent items.
:param agent_id: (required)
:type agent_id: str
:param fact_type:
:type fact_type: str
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:type _request_timeout: int, tuple(int, int), optional
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the
authentication in the spec for a single request.
:type _request_auth: dict, optional
:param _content_type: force content-type for the request.
:type _content_type: str, Optional
:param _headers: set to override the headers for a single
request; this effectively ignores the headers
in the spec for a single request.
:type _headers: dict, optional
:param _host_index: set to override the host_index for a single
request; this effectively ignores the host_index
in the spec for a single request.
:type _host_index: int, optional
:return: Returns the result object.
""" # noqa: E501
_param = self._get_graph_serialize(
agent_id=agent_id,
fact_type=fact_type,
_request_auth=_request_auth,
_content_type=_content_type,
_headers=_headers,
_host_index=_host_index
)
_response_types_map: Dict[str, Optional[str]] = {
'200': "GraphDataResponse",
'422': "HTTPValidationError",
}
response_data = await self.api_client.call_api(
*_param,
_request_timeout=_request_timeout
)
await response_data.read()
return self.api_client.response_deserialize(
response_data=response_data,
response_types_map=_response_types_map,
)
@validate_call
async def get_graph_without_preload_content(
self,
agent_id: StrictStr,
fact_type: Optional[StrictStr] = None,
_request_timeout: Union[
None,
Annotated[StrictFloat, Field(gt=0)],
Tuple[
Annotated[StrictFloat, Field(gt=0)],
Annotated[StrictFloat, Field(gt=0)]
]
] = None,
_request_auth: Optional[Dict[StrictStr, Any]] = None,
_content_type: Optional[StrictStr] = None,
_headers: Optional[Dict[StrictStr, Any]] = None,
_host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,
) -> RESTResponseType:
"""Get memory graph data
Retrieve graph data for visualization, optionally filtered by fact_type (world/agent/opinion). Limited to 1000 most recent items.
:param agent_id: (required)
:type agent_id: str
:param fact_type:
:type fact_type: str
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:type _request_timeout: int, tuple(int, int), optional
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the
authentication in the spec for a single request.
:type _request_auth: dict, optional
:param _content_type: force content-type for the request.
:type _content_type: str, Optional
:param _headers: set to override the headers for a single
request; this effectively ignores the headers
in the spec for a single request.
:type _headers: dict, optional
:param _host_index: set to override the host_index for a single
request; this effectively ignores the host_index
in the spec for a single request.
:type _host_index: int, optional
:return: Returns the result object.
""" # noqa: E501
_param = self._get_graph_serialize(
agent_id=agent_id,
fact_type=fact_type,
_request_auth=_request_auth,
_content_type=_content_type,
_headers=_headers,
_host_index=_host_index
)
_response_types_map: Dict[str, Optional[str]] = {
'200': "GraphDataResponse",
'422': "HTTPValidationError",
}
response_data = await self.api_client.call_api(
*_param,
_request_timeout=_request_timeout
)
return response_data.response
def _get_graph_serialize(
self,
agent_id,
fact_type,
_request_auth,
_content_type,
_headers,
_host_index,
) -> RequestSerialized:
_host = None
_collection_formats: Dict[str, str] = {
}
_path_params: Dict[str, str] = {}
_query_params: List[Tuple[str, str]] = []
_header_params: Dict[str, Optional[str]] = _headers or {}
_form_params: List[Tuple[str, str]] = []
_files: Dict[
str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]]
] = {}
_body_params: Optional[bytes] = None
# process the path parameters
if agent_id is not None:
_path_params['agent_id'] = agent_id
# process the query parameters
if fact_type is not None:
_query_params.append(('fact_type', fact_type))
# process the header parameters
# process the form parameters
# process the body parameter
# set the HTTP header `Accept`
if 'Accept' not in _header_params:
_header_params['Accept'] = self.api_client.select_header_accept(
[
'application/json'
]
)
# authentication setting
_auth_settings: List[str] = [
]
return self.api_client.param_serialize(
method='GET',
resource_path='/api/v1/agents/{agent_id}/graph',
path_params=_path_params,
query_params=_query_params,
header_params=_header_params,
body=_body_params,
post_params=_form_params,
files=_files,
auth_settings=_auth_settings,
collection_formats=_collection_formats,
_host=_host,
_request_auth=_request_auth
)

View file

@ -0,0 +1,807 @@
# coding: utf-8
"""
Agent Memory API
A temporal-semantic memory system for AI agents that stores, retrieves, and reasons over memories. ## Features * **Batch Memory Storage**: Store multiple memories efficiently with automatic fact extraction * **Semantic Search**: Find relevant memories using natural language queries * **Fact Type Filtering**: Search across world facts, agent actions, and opinions separately * **Think Endpoint**: Generate contextual answers based on agent identity and memories * **Graph Visualization**: Interactive memory graph visualization * **Document Tracking**: Track and manage memory documents with upsert support ## Architecture The system uses: - **Temporal Links**: Connect memories that are close in time - **Semantic Links**: Connect semantically similar memories - **Entity Links**: Connect memories that mention the same entities - **Spreading Activation**: Intelligent traversal for memory retrieval
The version of the OpenAPI document: 1.0.0
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import datetime
from dateutil.parser import parse
from enum import Enum
import decimal
import json
import mimetypes
import os
import re
import tempfile
import uuid
from urllib.parse import quote
from typing import Tuple, Optional, List, Dict, Union
from pydantic import SecretStr
from memora_client_api.configuration import Configuration
from memora_client_api.api_response import ApiResponse, T as ApiResponseT
import memora_client_api.models
from memora_client_api import rest
from memora_client_api.exceptions import (
ApiValueError,
ApiException,
BadRequestException,
UnauthorizedException,
ForbiddenException,
NotFoundException,
ServiceException
)
RequestSerialized = Tuple[str, str, Dict[str, str], Optional[str], List[str]]
class ApiClient:
"""Generic API client for OpenAPI client library builds.
OpenAPI generic API client. This client handles the client-
server communication, and is invariant across implementations. Specifics of
the methods and models for each application are generated from the OpenAPI
templates.
:param configuration: .Configuration object for this client
:param header_name: a header to pass when making calls to the API.
:param header_value: a header value to pass when making calls to
the API.
:param cookie: a cookie to include in the header when making calls
to the API
"""
PRIMITIVE_TYPES = (float, bool, bytes, str, int)
NATIVE_TYPES_MAPPING = {
'int': int,
'long': int, # TODO remove as only py3 is supported?
'float': float,
'str': str,
'bool': bool,
'date': datetime.date,
'datetime': datetime.datetime,
'decimal': decimal.Decimal,
'object': object,
}
_pool = None
def __init__(
self,
configuration=None,
header_name=None,
header_value=None,
cookie=None
) -> None:
# use default configuration if none is provided
if configuration is None:
configuration = Configuration.get_default()
self.configuration = configuration
self.rest_client = rest.RESTClientObject(configuration)
self.default_headers = {}
if header_name is not None:
self.default_headers[header_name] = header_value
self.cookie = cookie
# Set default User-Agent.
self.user_agent = 'OpenAPI-Generator/0.0.7/python'
self.client_side_validation = configuration.client_side_validation
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc_value, traceback):
await self.close()
async def close(self):
await self.rest_client.close()
@property
def user_agent(self):
"""User agent for this API client"""
return self.default_headers['User-Agent']
@user_agent.setter
def user_agent(self, value):
self.default_headers['User-Agent'] = value
def set_default_header(self, header_name, header_value):
self.default_headers[header_name] = header_value
_default = None
@classmethod
def get_default(cls):
"""Return new instance of ApiClient.
This method returns newly created, based on default constructor,
object of ApiClient class or returns a copy of default
ApiClient.
:return: The ApiClient object.
"""
if cls._default is None:
cls._default = ApiClient()
return cls._default
@classmethod
def set_default(cls, default):
"""Set default instance of ApiClient.
It stores default ApiClient.
:param default: object of ApiClient.
"""
cls._default = default
def param_serialize(
self,
method,
resource_path,
path_params=None,
query_params=None,
header_params=None,
body=None,
post_params=None,
files=None, auth_settings=None,
collection_formats=None,
_host=None,
_request_auth=None
) -> RequestSerialized:
"""Builds the HTTP request params needed by the request.
:param method: Method to call.
:param resource_path: Path to method endpoint.
:param path_params: Path parameters in the url.
:param query_params: Query parameters in the url.
:param header_params: Header parameters to be
placed in the request header.
:param body: Request body.
:param post_params dict: Request post form parameters,
for `application/x-www-form-urlencoded`, `multipart/form-data`.
:param auth_settings list: Auth Settings names for the request.
:param files dict: key -> filename, value -> filepath,
for `multipart/form-data`.
:param collection_formats: dict of collection formats for path, query,
header, and post parameters.
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the authentication
in the spec for a single request.
:return: tuple of form (path, http_method, query_params, header_params,
body, post_params, files)
"""
config = self.configuration
# header parameters
header_params = header_params or {}
header_params.update(self.default_headers)
if self.cookie:
header_params['Cookie'] = self.cookie
if header_params:
header_params = self.sanitize_for_serialization(header_params)
header_params = dict(
self.parameters_to_tuples(header_params,collection_formats)
)
# path parameters
if path_params:
path_params = self.sanitize_for_serialization(path_params)
path_params = self.parameters_to_tuples(
path_params,
collection_formats
)
for k, v in path_params:
# specified safe chars, encode everything
resource_path = resource_path.replace(
'{%s}' % k,
quote(str(v), safe=config.safe_chars_for_path_param)
)
# post parameters
if post_params or files:
post_params = post_params if post_params else []
post_params = self.sanitize_for_serialization(post_params)
post_params = self.parameters_to_tuples(
post_params,
collection_formats
)
if files:
post_params.extend(self.files_parameters(files))
# auth setting
self.update_params_for_auth(
header_params,
query_params,
auth_settings,
resource_path,
method,
body,
request_auth=_request_auth
)
# body
if body:
body = self.sanitize_for_serialization(body)
# request url
if _host is None or self.configuration.ignore_operation_servers:
url = self.configuration.host + resource_path
else:
# use server/host defined in path or operation instead
url = _host + resource_path
# query parameters
if query_params:
query_params = self.sanitize_for_serialization(query_params)
url_query = self.parameters_to_url_query(
query_params,
collection_formats
)
url += "?" + url_query
return method, url, header_params, body, post_params
async def call_api(
self,
method,
url,
header_params=None,
body=None,
post_params=None,
_request_timeout=None
) -> rest.RESTResponse:
"""Makes the HTTP request (synchronous)
:param method: Method to call.
:param url: Path to method endpoint.
:param header_params: Header parameters to be
placed in the request header.
:param body: Request body.
:param post_params dict: Request post form parameters,
for `application/x-www-form-urlencoded`, `multipart/form-data`.
:param _request_timeout: timeout setting for this request.
:return: RESTResponse
"""
try:
# perform request and return response
response_data = await self.rest_client.request(
method, url,
headers=header_params,
body=body, post_params=post_params,
_request_timeout=_request_timeout
)
except ApiException as e:
raise e
return response_data
def response_deserialize(
self,
response_data: rest.RESTResponse,
response_types_map: Optional[Dict[str, ApiResponseT]]=None
) -> ApiResponse[ApiResponseT]:
"""Deserializes response into an object.
:param response_data: RESTResponse object to be deserialized.
:param response_types_map: dict of response types.
:return: ApiResponse
"""
msg = "RESTResponse.read() must be called before passing it to response_deserialize()"
assert response_data.data is not None, msg
response_type = response_types_map.get(str(response_data.status), None)
if not response_type and isinstance(response_data.status, int) and 100 <= response_data.status <= 599:
# if not found, look for '1XX', '2XX', etc.
response_type = response_types_map.get(str(response_data.status)[0] + "XX", None)
# deserialize response data
response_text = None
return_data = None
try:
if response_type == "bytearray":
return_data = response_data.data
elif response_type == "file":
return_data = self.__deserialize_file(response_data)
elif response_type is not None:
match = None
content_type = response_data.getheader('content-type')
if content_type is not None:
match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type)
encoding = match.group(1) if match else "utf-8"
response_text = response_data.data.decode(encoding)
return_data = self.deserialize(response_text, response_type, content_type)
finally:
if not 200 <= response_data.status <= 299:
raise ApiException.from_response(
http_resp=response_data,
body=response_text,
data=return_data,
)
return ApiResponse(
status_code = response_data.status,
data = return_data,
headers = response_data.getheaders(),
raw_data = response_data.data
)
def sanitize_for_serialization(self, obj):
"""Builds a JSON POST object.
If obj is None, return None.
If obj is SecretStr, return obj.get_secret_value()
If obj is str, int, long, float, bool, return directly.
If obj is datetime.datetime, datetime.date
convert to string in iso8601 format.
If obj is decimal.Decimal return string representation.
If obj is list, sanitize each element in the list.
If obj is dict, return the dict.
If obj is OpenAPI model, return the properties dict.
:param obj: The data to serialize.
:return: The serialized form of data.
"""
if obj is None:
return None
elif isinstance(obj, Enum):
return obj.value
elif isinstance(obj, SecretStr):
return obj.get_secret_value()
elif isinstance(obj, self.PRIMITIVE_TYPES):
return obj
elif isinstance(obj, uuid.UUID):
return str(obj)
elif isinstance(obj, list):
return [
self.sanitize_for_serialization(sub_obj) for sub_obj in obj
]
elif isinstance(obj, tuple):
return tuple(
self.sanitize_for_serialization(sub_obj) for sub_obj in obj
)
elif isinstance(obj, (datetime.datetime, datetime.date)):
return obj.isoformat()
elif isinstance(obj, decimal.Decimal):
return str(obj)
elif isinstance(obj, dict):
obj_dict = obj
else:
# Convert model obj to dict except
# attributes `openapi_types`, `attribute_map`
# and attributes which value is not None.
# Convert attribute name to json key in
# model definition for request.
if hasattr(obj, 'to_dict') and callable(getattr(obj, 'to_dict')):
obj_dict = obj.to_dict()
else:
obj_dict = obj.__dict__
if isinstance(obj_dict, list):
# here we handle instances that can either be a list or something else, and only became a real list by calling to_dict()
return self.sanitize_for_serialization(obj_dict)
return {
key: self.sanitize_for_serialization(val)
for key, val in obj_dict.items()
}
def deserialize(self, response_text: str, response_type: str, content_type: Optional[str]):
"""Deserializes response into an object.
:param response: RESTResponse object to be deserialized.
:param response_type: class literal for
deserialized object, or string of class name.
:param content_type: content type of response.
:return: deserialized object.
"""
# fetch data from response object
if content_type is None:
try:
data = json.loads(response_text)
except ValueError:
data = response_text
elif re.match(r'^application/(json|[\w!#$&.+\-^_]+\+json)\s*(;|$)', content_type, re.IGNORECASE):
if response_text == "":
data = ""
else:
data = json.loads(response_text)
elif re.match(r'^text\/[a-z.+-]+\s*(;|$)', content_type, re.IGNORECASE):
data = response_text
else:
raise ApiException(
status=0,
reason="Unsupported content type: {0}".format(content_type)
)
return self.__deserialize(data, response_type)
def __deserialize(self, data, klass):
"""Deserializes dict, list, str into an object.
:param data: dict, list or str.
:param klass: class literal, or string of class name.
:return: object.
"""
if data is None:
return None
if isinstance(klass, str):
if klass.startswith('List['):
m = re.match(r'List\[(.*)]', klass)
assert m is not None, "Malformed List type definition"
sub_kls = m.group(1)
return [self.__deserialize(sub_data, sub_kls)
for sub_data in data]
if klass.startswith('Dict['):
m = re.match(r'Dict\[([^,]*), (.*)]', klass)
assert m is not None, "Malformed Dict type definition"
sub_kls = m.group(2)
return {k: self.__deserialize(v, sub_kls)
for k, v in data.items()}
# convert str to class
if klass in self.NATIVE_TYPES_MAPPING:
klass = self.NATIVE_TYPES_MAPPING[klass]
else:
klass = getattr(memora_client_api.models, klass)
if klass in self.PRIMITIVE_TYPES:
return self.__deserialize_primitive(data, klass)
elif klass is object:
return self.__deserialize_object(data)
elif klass is datetime.date:
return self.__deserialize_date(data)
elif klass is datetime.datetime:
return self.__deserialize_datetime(data)
elif klass is decimal.Decimal:
return decimal.Decimal(data)
elif issubclass(klass, Enum):
return self.__deserialize_enum(data, klass)
else:
return self.__deserialize_model(data, klass)
def parameters_to_tuples(self, params, collection_formats):
"""Get parameters as list of tuples, formatting collections.
:param params: Parameters as dict or list of two-tuples
:param dict collection_formats: Parameter collection formats
:return: Parameters as list of tuples, collections formatted
"""
new_params: List[Tuple[str, str]] = []
if collection_formats is None:
collection_formats = {}
for k, v in params.items() if isinstance(params, dict) else params:
if k in collection_formats:
collection_format = collection_formats[k]
if collection_format == 'multi':
new_params.extend((k, value) for value in v)
else:
if collection_format == 'ssv':
delimiter = ' '
elif collection_format == 'tsv':
delimiter = '\t'
elif collection_format == 'pipes':
delimiter = '|'
else: # csv is the default
delimiter = ','
new_params.append(
(k, delimiter.join(str(value) for value in v)))
else:
new_params.append((k, v))
return new_params
def parameters_to_url_query(self, params, collection_formats):
"""Get parameters as list of tuples, formatting collections.
:param params: Parameters as dict or list of two-tuples
:param dict collection_formats: Parameter collection formats
:return: URL query string (e.g. a=Hello%20World&b=123)
"""
new_params: List[Tuple[str, str]] = []
if collection_formats is None:
collection_formats = {}
for k, v in params.items() if isinstance(params, dict) else params:
if isinstance(v, bool):
v = str(v).lower()
if isinstance(v, (int, float)):
v = str(v)
if isinstance(v, dict):
v = json.dumps(v)
if k in collection_formats:
collection_format = collection_formats[k]
if collection_format == 'multi':
new_params.extend((k, quote(str(value))) for value in v)
else:
if collection_format == 'ssv':
delimiter = ' '
elif collection_format == 'tsv':
delimiter = '\t'
elif collection_format == 'pipes':
delimiter = '|'
else: # csv is the default
delimiter = ','
new_params.append(
(k, delimiter.join(quote(str(value)) for value in v))
)
else:
new_params.append((k, quote(str(v))))
return "&".join(["=".join(map(str, item)) for item in new_params])
def files_parameters(
self,
files: Dict[str, Union[str, bytes, List[str], List[bytes], Tuple[str, bytes]]],
):
"""Builds form parameters.
:param files: File parameters.
:return: Form parameters with files.
"""
params = []
for k, v in files.items():
if isinstance(v, str):
with open(v, 'rb') as f:
filename = os.path.basename(f.name)
filedata = f.read()
elif isinstance(v, bytes):
filename = k
filedata = v
elif isinstance(v, tuple):
filename, filedata = v
elif isinstance(v, list):
for file_param in v:
params.extend(self.files_parameters({k: file_param}))
continue
else:
raise ValueError("Unsupported file value")
mimetype = (
mimetypes.guess_type(filename)[0]
or 'application/octet-stream'
)
params.append(
tuple([k, tuple([filename, filedata, mimetype])])
)
return params
def select_header_accept(self, accepts: List[str]) -> Optional[str]:
"""Returns `Accept` based on an array of accepts provided.
:param accepts: List of headers.
:return: Accept (e.g. application/json).
"""
if not accepts:
return None
for accept in accepts:
if re.search('json', accept, re.IGNORECASE):
return accept
return accepts[0]
def select_header_content_type(self, content_types):
"""Returns `Content-Type` based on an array of content_types provided.
:param content_types: List of content-types.
:return: Content-Type (e.g. application/json).
"""
if not content_types:
return None
for content_type in content_types:
if re.search('json', content_type, re.IGNORECASE):
return content_type
return content_types[0]
def update_params_for_auth(
self,
headers,
queries,
auth_settings,
resource_path,
method,
body,
request_auth=None
) -> None:
"""Updates header and query params based on authentication setting.
:param headers: Header parameters dict to be updated.
:param queries: Query parameters tuple list to be updated.
:param auth_settings: Authentication setting identifiers list.
:resource_path: A string representation of the HTTP request resource path.
:method: A string representation of the HTTP request method.
:body: A object representing the body of the HTTP request.
The object type is the return value of sanitize_for_serialization().
:param request_auth: if set, the provided settings will
override the token in the configuration.
"""
if not auth_settings:
return
if request_auth:
self._apply_auth_params(
headers,
queries,
resource_path,
method,
body,
request_auth
)
else:
for auth in auth_settings:
auth_setting = self.configuration.auth_settings().get(auth)
if auth_setting:
self._apply_auth_params(
headers,
queries,
resource_path,
method,
body,
auth_setting
)
def _apply_auth_params(
self,
headers,
queries,
resource_path,
method,
body,
auth_setting
) -> None:
"""Updates the request parameters based on a single auth_setting
:param headers: Header parameters dict to be updated.
:param queries: Query parameters tuple list to be updated.
:resource_path: A string representation of the HTTP request resource path.
:method: A string representation of the HTTP request method.
:body: A object representing the body of the HTTP request.
The object type is the return value of sanitize_for_serialization().
:param auth_setting: auth settings for the endpoint
"""
if auth_setting['in'] == 'cookie':
headers['Cookie'] = auth_setting['value']
elif auth_setting['in'] == 'header':
if auth_setting['type'] != 'http-signature':
headers[auth_setting['key']] = auth_setting['value']
elif auth_setting['in'] == 'query':
queries.append((auth_setting['key'], auth_setting['value']))
else:
raise ApiValueError(
'Authentication token must be in `query` or `header`'
)
def __deserialize_file(self, response):
"""Deserializes body to file
Saves response body into a file in a temporary folder,
using the filename from the `Content-Disposition` header if provided.
handle file downloading
save response body into a tmp file and return the instance
:param response: RESTResponse.
:return: file path.
"""
fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path)
os.close(fd)
os.remove(path)
content_disposition = response.getheader("Content-Disposition")
if content_disposition:
m = re.search(
r'filename=[\'"]?([^\'"\s]+)[\'"]?',
content_disposition
)
assert m is not None, "Unexpected 'content-disposition' header value"
filename = m.group(1)
path = os.path.join(os.path.dirname(path), filename)
with open(path, "wb") as f:
f.write(response.data)
return path
def __deserialize_primitive(self, data, klass):
"""Deserializes string to primitive type.
:param data: str.
:param klass: class literal.
:return: int, long, float, str, bool.
"""
try:
return klass(data)
except UnicodeEncodeError:
return str(data)
except TypeError:
return data
def __deserialize_object(self, value):
"""Return an original value.
:return: object.
"""
return value
def __deserialize_date(self, string):
"""Deserializes string to date.
:param string: str.
:return: date.
"""
try:
return parse(string).date()
except ImportError:
return string
except ValueError:
raise rest.ApiException(
status=0,
reason="Failed to parse `{0}` as date object".format(string)
)
def __deserialize_datetime(self, string):
"""Deserializes string to datetime.
The string should be in iso8601 datetime format.
:param string: str.
:return: datetime.
"""
try:
return parse(string)
except ImportError:
return string
except ValueError:
raise rest.ApiException(
status=0,
reason=(
"Failed to parse `{0}` as datetime object"
.format(string)
)
)
def __deserialize_enum(self, data, klass):
"""Deserializes primitive type to enum.
:param data: primitive type.
:param klass: class literal.
:return: enum value.
"""
try:
return klass(data)
except ValueError:
raise rest.ApiException(
status=0,
reason=(
"Failed to parse `{0}` as `{1}`"
.format(data, klass)
)
)
def __deserialize_model(self, data, klass):
"""Deserializes list or dict to model.
:param data: dict, list.
:param klass: class literal.
:return: model object.
"""
return klass.from_dict(data)

View file

@ -0,0 +1,21 @@
"""API response object."""
from __future__ import annotations
from typing import Optional, Generic, Mapping, TypeVar
from pydantic import Field, StrictInt, StrictBytes, BaseModel
T = TypeVar("T")
class ApiResponse(BaseModel, Generic[T]):
"""
API response object
"""
status_code: StrictInt = Field(description="HTTP status code")
headers: Optional[Mapping[str, str]] = Field(None, description="HTTP headers")
data: T = Field(description="Deserialized data given the data type")
raw_data: StrictBytes = Field(description="Raw data (HTTP response body)")
model_config = {
"arbitrary_types_allowed": True
}

View file

@ -0,0 +1,572 @@
# coding: utf-8
"""
Agent Memory API
A temporal-semantic memory system for AI agents that stores, retrieves, and reasons over memories. ## Features * **Batch Memory Storage**: Store multiple memories efficiently with automatic fact extraction * **Semantic Search**: Find relevant memories using natural language queries * **Fact Type Filtering**: Search across world facts, agent actions, and opinions separately * **Think Endpoint**: Generate contextual answers based on agent identity and memories * **Graph Visualization**: Interactive memory graph visualization * **Document Tracking**: Track and manage memory documents with upsert support ## Architecture The system uses: - **Temporal Links**: Connect memories that are close in time - **Semantic Links**: Connect semantically similar memories - **Entity Links**: Connect memories that mention the same entities - **Spreading Activation**: Intelligent traversal for memory retrieval
The version of the OpenAPI document: 1.0.0
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import copy
import http.client as httplib
import logging
from logging import FileHandler
import sys
from typing import Any, ClassVar, Dict, List, Literal, Optional, TypedDict, Union
from typing_extensions import NotRequired, Self
import urllib3
JSON_SCHEMA_VALIDATION_KEYWORDS = {
'multipleOf', 'maximum', 'exclusiveMaximum',
'minimum', 'exclusiveMinimum', 'maxLength',
'minLength', 'pattern', 'maxItems', 'minItems'
}
ServerVariablesT = Dict[str, str]
GenericAuthSetting = TypedDict(
"GenericAuthSetting",
{
"type": str,
"in": str,
"key": str,
"value": str,
},
)
OAuth2AuthSetting = TypedDict(
"OAuth2AuthSetting",
{
"type": Literal["oauth2"],
"in": Literal["header"],
"key": Literal["Authorization"],
"value": str,
},
)
APIKeyAuthSetting = TypedDict(
"APIKeyAuthSetting",
{
"type": Literal["api_key"],
"in": str,
"key": str,
"value": Optional[str],
},
)
BasicAuthSetting = TypedDict(
"BasicAuthSetting",
{
"type": Literal["basic"],
"in": Literal["header"],
"key": Literal["Authorization"],
"value": Optional[str],
},
)
BearerFormatAuthSetting = TypedDict(
"BearerFormatAuthSetting",
{
"type": Literal["bearer"],
"in": Literal["header"],
"format": Literal["JWT"],
"key": Literal["Authorization"],
"value": str,
},
)
BearerAuthSetting = TypedDict(
"BearerAuthSetting",
{
"type": Literal["bearer"],
"in": Literal["header"],
"key": Literal["Authorization"],
"value": str,
},
)
HTTPSignatureAuthSetting = TypedDict(
"HTTPSignatureAuthSetting",
{
"type": Literal["http-signature"],
"in": Literal["header"],
"key": Literal["Authorization"],
"value": None,
},
)
AuthSettings = TypedDict(
"AuthSettings",
{
},
total=False,
)
class HostSettingVariable(TypedDict):
description: str
default_value: str
enum_values: List[str]
class HostSetting(TypedDict):
url: str
description: str
variables: NotRequired[Dict[str, HostSettingVariable]]
class Configuration:
"""This class contains various settings of the API client.
:param host: Base url.
:param ignore_operation_servers
Boolean to ignore operation servers for the API client.
Config will use `host` as the base url regardless of the operation servers.
:param api_key: Dict to store API key(s).
Each entry in the dict specifies an API key.
The dict key is the name of the security scheme in the OAS specification.
The dict value is the API key secret.
:param api_key_prefix: Dict to store API prefix (e.g. Bearer).
The dict key is the name of the security scheme in the OAS specification.
The dict value is an API key prefix when generating the auth data.
:param username: Username for HTTP basic authentication.
:param password: Password for HTTP basic authentication.
:param access_token: Access token.
:param server_index: Index to servers configuration.
:param server_variables: Mapping with string values to replace variables in
templated server configuration. The validation of enums is performed for
variables with defined enum values before.
:param server_operation_index: Mapping from operation ID to an index to server
configuration.
:param server_operation_variables: Mapping from operation ID to a mapping with
string values to replace variables in templated server configuration.
The validation of enums is performed for variables with defined enum
values before.
:param ssl_ca_cert: str - the path to a file of concatenated CA certificates
in PEM format.
:param retries: Number of retries for API requests.
:param ca_cert_data: verify the peer using concatenated CA certificate data
in PEM (str) or DER (bytes) format.
:param cert_file: the path to a client certificate file, for mTLS.
:param key_file: the path to a client key file, for mTLS.
"""
_default: ClassVar[Optional[Self]] = None
def __init__(
self,
host: Optional[str]=None,
api_key: Optional[Dict[str, str]]=None,
api_key_prefix: Optional[Dict[str, str]]=None,
username: Optional[str]=None,
password: Optional[str]=None,
access_token: Optional[str]=None,
server_index: Optional[int]=None,
server_variables: Optional[ServerVariablesT]=None,
server_operation_index: Optional[Dict[int, int]]=None,
server_operation_variables: Optional[Dict[int, ServerVariablesT]]=None,
ignore_operation_servers: bool=False,
ssl_ca_cert: Optional[str]=None,
retries: Optional[int] = None,
ca_cert_data: Optional[Union[str, bytes]] = None,
cert_file: Optional[str]=None,
key_file: Optional[str]=None,
*,
debug: Optional[bool] = None,
) -> None:
"""Constructor
"""
self._base_path = "http://localhost" if host is None else host
"""Default Base url
"""
self.server_index = 0 if server_index is None and host is None else server_index
self.server_operation_index = server_operation_index or {}
"""Default server index
"""
self.server_variables = server_variables or {}
self.server_operation_variables = server_operation_variables or {}
"""Default server variables
"""
self.ignore_operation_servers = ignore_operation_servers
"""Ignore operation servers
"""
self.temp_folder_path = None
"""Temp file folder for downloading files
"""
# Authentication Settings
self.api_key = {}
if api_key:
self.api_key = api_key
"""dict to store API key(s)
"""
self.api_key_prefix = {}
if api_key_prefix:
self.api_key_prefix = api_key_prefix
"""dict to store API prefix (e.g. Bearer)
"""
self.refresh_api_key_hook = None
"""function hook to refresh API key if expired
"""
self.username = username
"""Username for HTTP basic authentication
"""
self.password = password
"""Password for HTTP basic authentication
"""
self.access_token = access_token
"""Access token
"""
self.logger = {}
"""Logging Settings
"""
self.logger["package_logger"] = logging.getLogger("memora_client_api")
self.logger["urllib3_logger"] = logging.getLogger("urllib3")
self.logger_format = '%(asctime)s %(levelname)s %(message)s'
"""Log format
"""
self.logger_stream_handler = None
"""Log stream handler
"""
self.logger_file_handler: Optional[FileHandler] = None
"""Log file handler
"""
self.logger_file = None
"""Debug file location
"""
if debug is not None:
self.debug = debug
else:
self.__debug = False
"""Debug switch
"""
self.verify_ssl = True
"""SSL/TLS verification
Set this to false to skip verifying SSL certificate when calling API
from https server.
"""
self.ssl_ca_cert = ssl_ca_cert
"""Set this to customize the certificate file to verify the peer.
"""
self.ca_cert_data = ca_cert_data
"""Set this to verify the peer using PEM (str) or DER (bytes)
certificate data.
"""
self.cert_file = cert_file
"""client certificate file
"""
self.key_file = key_file
"""client key file
"""
self.assert_hostname = None
"""Set this to True/False to enable/disable SSL hostname verification.
"""
self.tls_server_name = None
"""SSL/TLS Server Name Indication (SNI)
Set this to the SNI value expected by the server.
"""
self.connection_pool_maxsize = 100
"""This value is passed to the aiohttp to limit simultaneous connections.
Default values is 100, None means no-limit.
"""
self.proxy: Optional[str] = None
"""Proxy URL
"""
self.proxy_headers = None
"""Proxy headers
"""
self.safe_chars_for_path_param = ''
"""Safe chars for path_param
"""
self.retries = retries
"""Adding retries to override urllib3 default value 3
"""
# Enable client side validation
self.client_side_validation = True
self.socket_options = None
"""Options to pass down to the underlying urllib3 socket
"""
self.datetime_format = "%Y-%m-%dT%H:%M:%S.%f%z"
"""datetime format
"""
self.date_format = "%Y-%m-%d"
"""date format
"""
def __deepcopy__(self, memo: Dict[int, Any]) -> Self:
cls = self.__class__
result = cls.__new__(cls)
memo[id(self)] = result
for k, v in self.__dict__.items():
if k not in ('logger', 'logger_file_handler'):
setattr(result, k, copy.deepcopy(v, memo))
# shallow copy of loggers
result.logger = copy.copy(self.logger)
# use setters to configure loggers
result.logger_file = self.logger_file
result.debug = self.debug
return result
def __setattr__(self, name: str, value: Any) -> None:
object.__setattr__(self, name, value)
@classmethod
def set_default(cls, default: Optional[Self]) -> None:
"""Set default instance of configuration.
It stores default configuration, which can be
returned by get_default_copy method.
:param default: object of Configuration
"""
cls._default = default
@classmethod
def get_default_copy(cls) -> Self:
"""Deprecated. Please use `get_default` instead.
Deprecated. Please use `get_default` instead.
:return: The configuration object.
"""
return cls.get_default()
@classmethod
def get_default(cls) -> Self:
"""Return the default configuration.
This method returns newly created, based on default constructor,
object of Configuration class or returns a copy of default
configuration.
:return: The configuration object.
"""
if cls._default is None:
cls._default = cls()
return cls._default
@property
def logger_file(self) -> Optional[str]:
"""The logger file.
If the logger_file is None, then add stream handler and remove file
handler. Otherwise, add file handler and remove stream handler.
:param value: The logger_file path.
:type: str
"""
return self.__logger_file
@logger_file.setter
def logger_file(self, value: Optional[str]) -> None:
"""The logger file.
If the logger_file is None, then add stream handler and remove file
handler. Otherwise, add file handler and remove stream handler.
:param value: The logger_file path.
:type: str
"""
self.__logger_file = value
if self.__logger_file:
# If set logging file,
# then add file handler and remove stream handler.
self.logger_file_handler = logging.FileHandler(self.__logger_file)
self.logger_file_handler.setFormatter(self.logger_formatter)
for _, logger in self.logger.items():
logger.addHandler(self.logger_file_handler)
@property
def debug(self) -> bool:
"""Debug status
:param value: The debug status, True or False.
:type: bool
"""
return self.__debug
@debug.setter
def debug(self, value: bool) -> None:
"""Debug status
:param value: The debug status, True or False.
:type: bool
"""
self.__debug = value
if self.__debug:
# if debug status is True, turn on debug logging
for _, logger in self.logger.items():
logger.setLevel(logging.DEBUG)
# turn on httplib debug
httplib.HTTPConnection.debuglevel = 1
else:
# if debug status is False, turn off debug logging,
# setting log level to default `logging.WARNING`
for _, logger in self.logger.items():
logger.setLevel(logging.WARNING)
# turn off httplib debug
httplib.HTTPConnection.debuglevel = 0
@property
def logger_format(self) -> str:
"""The logger format.
The logger_formatter will be updated when sets logger_format.
:param value: The format string.
:type: str
"""
return self.__logger_format
@logger_format.setter
def logger_format(self, value: str) -> None:
"""The logger format.
The logger_formatter will be updated when sets logger_format.
:param value: The format string.
:type: str
"""
self.__logger_format = value
self.logger_formatter = logging.Formatter(self.__logger_format)
def get_api_key_with_prefix(self, identifier: str, alias: Optional[str]=None) -> Optional[str]:
"""Gets API key (with prefix if set).
:param identifier: The identifier of apiKey.
:param alias: The alternative identifier of apiKey.
:return: The token for api key authentication.
"""
if self.refresh_api_key_hook is not None:
self.refresh_api_key_hook(self)
key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None)
if key:
prefix = self.api_key_prefix.get(identifier)
if prefix:
return "%s %s" % (prefix, key)
else:
return key
return None
def get_basic_auth_token(self) -> Optional[str]:
"""Gets HTTP basic authentication header (string).
:return: The token for basic HTTP authentication.
"""
username = ""
if self.username is not None:
username = self.username
password = ""
if self.password is not None:
password = self.password
return urllib3.util.make_headers(
basic_auth=username + ':' + password
).get('authorization')
def auth_settings(self)-> AuthSettings:
"""Gets Auth Settings dict for api client.
:return: The Auth Settings information dict.
"""
auth: AuthSettings = {}
return auth
def to_debug_report(self) -> str:
"""Gets the essential information for debugging.
:return: The report for debugging.
"""
return "Python SDK Debug Report:\n"\
"OS: {env}\n"\
"Python Version: {pyversion}\n"\
"Version of the API: 1.0.0\n"\
"SDK Package Version: 0.0.7".\
format(env=sys.platform, pyversion=sys.version)
def get_host_settings(self) -> List[HostSetting]:
"""Gets an array of host settings
:return: An array of host settings
"""
return [
{
'url': "",
'description': "No description provided",
}
]
def get_host_from_settings(
self,
index: Optional[int],
variables: Optional[ServerVariablesT]=None,
servers: Optional[List[HostSetting]]=None,
) -> str:
"""Gets host URL based on the index and variables
:param index: array index of the host settings
:param variables: hash of variable and the corresponding value
:param servers: an array of host settings or None
:return: URL based on host settings
"""
if index is None:
return self._base_path
variables = {} if variables is None else variables
servers = self.get_host_settings() if servers is None else servers
try:
server = servers[index]
except IndexError:
raise ValueError(
"Invalid index {0} when selecting the host settings. "
"Must be less than {1}".format(index, len(servers)))
url = server['url']
# go through variables and replace placeholders
for variable_name, variable in server.get('variables', {}).items():
used_value = variables.get(
variable_name, variable['default_value'])
if 'enum_values' in variable \
and used_value not in variable['enum_values']:
raise ValueError(
"The variable `{0}` in the host URL has invalid value "
"{1}. Must be {2}.".format(
variable_name, variables[variable_name],
variable['enum_values']))
url = url.replace("{" + variable_name + "}", used_value)
return url
@property
def host(self) -> str:
"""Return generated host."""
return self.get_host_from_settings(self.server_index, variables=self.server_variables)
@host.setter
def host(self, value: str) -> None:
"""Fix base path."""
self._base_path = value
self.server_index = None

View file

@ -0,0 +1,31 @@
# AddBackgroundRequest
Request model for adding/merging background information.
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**content** | **str** | New background information to add or merge |
**update_personality** | **bool** | If true, infer Big Five personality traits from the merged background (default: true) | [optional] [default to True]
## Example
```python
from memora_client_api.models.add_background_request import AddBackgroundRequest
# TODO update the JSON string below
json = "{}"
# create an instance of AddBackgroundRequest from a JSON string
add_background_request_instance = AddBackgroundRequest.from_json(json)
# print the JSON string representation of the object
print(AddBackgroundRequest.to_json())
# convert the object into a dict
add_background_request_dict = add_background_request_instance.to_dict()
# create an instance of AddBackgroundRequest from a dict
add_background_request_from_dict = AddBackgroundRequest.from_dict(add_background_request_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View file

@ -0,0 +1,35 @@
# AgentListItem
Agent list item with profile summary.
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**agent_id** | **str** | |
**name** | **str** | |
**personality** | [**PersonalityTraits**](PersonalityTraits.md) | |
**background** | **str** | |
**created_at** | **str** | | [optional]
**updated_at** | **str** | | [optional]
## Example
```python
from memora_client_api.models.agent_list_item import AgentListItem
# TODO update the JSON string below
json = "{}"
# create an instance of AgentListItem from a JSON string
agent_list_item_instance = AgentListItem.from_json(json)
# print the JSON string representation of the object
print(AgentListItem.to_json())
# convert the object into a dict
agent_list_item_dict = agent_list_item_instance.to_dict()
# create an instance of AgentListItem from a dict
agent_list_item_from_dict = AgentListItem.from_dict(agent_list_item_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View file

@ -0,0 +1,30 @@
# AgentListResponse
Response model for listing all agents.
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**agents** | [**List[AgentListItem]**](AgentListItem.md) | |
## Example
```python
from memora_client_api.models.agent_list_response import AgentListResponse
# TODO update the JSON string below
json = "{}"
# create an instance of AgentListResponse from a JSON string
agent_list_response_instance = AgentListResponse.from_json(json)
# print the JSON string representation of the object
print(AgentListResponse.to_json())
# convert the object into a dict
agent_list_response_dict = agent_list_response_instance.to_dict()
# create an instance of AgentListResponse from a dict
agent_list_response_from_dict = AgentListResponse.from_dict(agent_list_response_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View file

@ -0,0 +1,503 @@
# memora_client_api.AgentManagementApi
All URIs are relative to *http://localhost*
Method | HTTP request | Description
------------- | ------------- | -------------
[**add_agent_background**](AgentManagementApi.md#add_agent_background) | **POST** /api/v1/agents/{agent_id}/background | Add/merge agent background
[**clear_agent_memories**](AgentManagementApi.md#clear_agent_memories) | **DELETE** /api/v1/agents/{agent_id}/memories | Clear agent memories
[**create_or_update_agent**](AgentManagementApi.md#create_or_update_agent) | **PUT** /api/v1/agents/{agent_id} | Create or update agent
[**get_agent_profile**](AgentManagementApi.md#get_agent_profile) | **GET** /api/v1/agents/{agent_id}/profile | Get agent profile
[**get_agent_stats**](AgentManagementApi.md#get_agent_stats) | **GET** /api/v1/agents/{agent_id}/stats | Get memory statistics for an agent
[**list_agents**](AgentManagementApi.md#list_agents) | **GET** /api/v1/agents | List all agents
[**update_agent_personality**](AgentManagementApi.md#update_agent_personality) | **PUT** /api/v1/agents/{agent_id}/profile | Update agent personality
# **add_agent_background**
> BackgroundResponse add_agent_background(agent_id, add_background_request)
Add/merge agent background
Add new background information or merge with existing. LLM intelligently resolves conflicts, normalizes to first person, and optionally infers personality traits.
### Example
```python
import memora_client_api
from memora_client_api.models.add_background_request import AddBackgroundRequest
from memora_client_api.models.background_response import BackgroundResponse
from memora_client_api.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost
# See configuration.py for a list of all supported configuration parameters.
configuration = memora_client_api.Configuration(
host = "http://localhost"
)
# Enter a context with an instance of the API client
async with memora_client_api.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = memora_client_api.AgentManagementApi(api_client)
agent_id = 'agent_id_example' # str |
add_background_request = memora_client_api.AddBackgroundRequest() # AddBackgroundRequest |
try:
# Add/merge agent background
api_response = await api_instance.add_agent_background(agent_id, add_background_request)
print("The response of AgentManagementApi->add_agent_background:\n")
pprint(api_response)
except Exception as e:
print("Exception when calling AgentManagementApi->add_agent_background: %s\n" % e)
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**agent_id** | **str**| |
**add_background_request** | [**AddBackgroundRequest**](AddBackgroundRequest.md)| |
### Return type
[**BackgroundResponse**](BackgroundResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | Successful Response | - |
**422** | Validation Error | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **clear_agent_memories**
> DeleteResponse clear_agent_memories(agent_id, fact_type=fact_type)
Clear agent memories
Delete memory units for an agent. Optionally filter by fact_type (world, agent, opinion) to delete only specific types. This is a destructive operation that cannot be undone. The agent profile (personality and background) will be preserved.
### Example
```python
import memora_client_api
from memora_client_api.models.delete_response import DeleteResponse
from memora_client_api.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost
# See configuration.py for a list of all supported configuration parameters.
configuration = memora_client_api.Configuration(
host = "http://localhost"
)
# Enter a context with an instance of the API client
async with memora_client_api.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = memora_client_api.AgentManagementApi(api_client)
agent_id = 'agent_id_example' # str |
fact_type = 'fact_type_example' # str | Optional fact type filter (world, agent, opinion) (optional)
try:
# Clear agent memories
api_response = await api_instance.clear_agent_memories(agent_id, fact_type=fact_type)
print("The response of AgentManagementApi->clear_agent_memories:\n")
pprint(api_response)
except Exception as e:
print("Exception when calling AgentManagementApi->clear_agent_memories: %s\n" % e)
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**agent_id** | **str**| |
**fact_type** | **str**| Optional fact type filter (world, agent, opinion) | [optional]
### Return type
[**DeleteResponse**](DeleteResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | Successful Response | - |
**422** | Validation Error | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **create_or_update_agent**
> AgentProfileResponse create_or_update_agent(agent_id, create_agent_request)
Create or update agent
Create a new agent or update existing agent with personality and background. Auto-fills missing fields with defaults.
### Example
```python
import memora_client_api
from memora_client_api.models.agent_profile_response import AgentProfileResponse
from memora_client_api.models.create_agent_request import CreateAgentRequest
from memora_client_api.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost
# See configuration.py for a list of all supported configuration parameters.
configuration = memora_client_api.Configuration(
host = "http://localhost"
)
# Enter a context with an instance of the API client
async with memora_client_api.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = memora_client_api.AgentManagementApi(api_client)
agent_id = 'agent_id_example' # str |
create_agent_request = memora_client_api.CreateAgentRequest() # CreateAgentRequest |
try:
# Create or update agent
api_response = await api_instance.create_or_update_agent(agent_id, create_agent_request)
print("The response of AgentManagementApi->create_or_update_agent:\n")
pprint(api_response)
except Exception as e:
print("Exception when calling AgentManagementApi->create_or_update_agent: %s\n" % e)
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**agent_id** | **str**| |
**create_agent_request** | [**CreateAgentRequest**](CreateAgentRequest.md)| |
### Return type
[**AgentProfileResponse**](AgentProfileResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | Successful Response | - |
**422** | Validation Error | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **get_agent_profile**
> AgentProfileResponse get_agent_profile(agent_id)
Get agent profile
Get personality traits and background for an agent. Auto-creates agent with defaults if not exists.
### Example
```python
import memora_client_api
from memora_client_api.models.agent_profile_response import AgentProfileResponse
from memora_client_api.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost
# See configuration.py for a list of all supported configuration parameters.
configuration = memora_client_api.Configuration(
host = "http://localhost"
)
# Enter a context with an instance of the API client
async with memora_client_api.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = memora_client_api.AgentManagementApi(api_client)
agent_id = 'agent_id_example' # str |
try:
# Get agent profile
api_response = await api_instance.get_agent_profile(agent_id)
print("The response of AgentManagementApi->get_agent_profile:\n")
pprint(api_response)
except Exception as e:
print("Exception when calling AgentManagementApi->get_agent_profile: %s\n" % e)
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**agent_id** | **str**| |
### Return type
[**AgentProfileResponse**](AgentProfileResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | Successful Response | - |
**422** | Validation Error | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **get_agent_stats**
> object get_agent_stats(agent_id)
Get memory statistics for an agent
Get statistics about nodes and links for a specific agent
### Example
```python
import memora_client_api
from memora_client_api.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost
# See configuration.py for a list of all supported configuration parameters.
configuration = memora_client_api.Configuration(
host = "http://localhost"
)
# Enter a context with an instance of the API client
async with memora_client_api.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = memora_client_api.AgentManagementApi(api_client)
agent_id = 'agent_id_example' # str |
try:
# Get memory statistics for an agent
api_response = await api_instance.get_agent_stats(agent_id)
print("The response of AgentManagementApi->get_agent_stats:\n")
pprint(api_response)
except Exception as e:
print("Exception when calling AgentManagementApi->get_agent_stats: %s\n" % e)
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**agent_id** | **str**| |
### Return type
**object**
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | Successful Response | - |
**422** | Validation Error | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **list_agents**
> AgentListResponse list_agents()
List all agents
Get a list of all agents with their profiles
### Example
```python
import memora_client_api
from memora_client_api.models.agent_list_response import AgentListResponse
from memora_client_api.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost
# See configuration.py for a list of all supported configuration parameters.
configuration = memora_client_api.Configuration(
host = "http://localhost"
)
# Enter a context with an instance of the API client
async with memora_client_api.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = memora_client_api.AgentManagementApi(api_client)
try:
# List all agents
api_response = await api_instance.list_agents()
print("The response of AgentManagementApi->list_agents:\n")
pprint(api_response)
except Exception as e:
print("Exception when calling AgentManagementApi->list_agents: %s\n" % e)
```
### Parameters
This endpoint does not need any parameter.
### Return type
[**AgentListResponse**](AgentListResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | Successful Response | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **update_agent_personality**
> AgentProfileResponse update_agent_personality(agent_id, update_personality_request)
Update agent personality
Update agent's Big Five personality traits and bias strength
### Example
```python
import memora_client_api
from memora_client_api.models.agent_profile_response import AgentProfileResponse
from memora_client_api.models.update_personality_request import UpdatePersonalityRequest
from memora_client_api.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost
# See configuration.py for a list of all supported configuration parameters.
configuration = memora_client_api.Configuration(
host = "http://localhost"
)
# Enter a context with an instance of the API client
async with memora_client_api.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = memora_client_api.AgentManagementApi(api_client)
agent_id = 'agent_id_example' # str |
update_personality_request = memora_client_api.UpdatePersonalityRequest() # UpdatePersonalityRequest |
try:
# Update agent personality
api_response = await api_instance.update_agent_personality(agent_id, update_personality_request)
print("The response of AgentManagementApi->update_agent_personality:\n")
pprint(api_response)
except Exception as e:
print("Exception when calling AgentManagementApi->update_agent_personality: %s\n" % e)
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**agent_id** | **str**| |
**update_personality_request** | [**UpdatePersonalityRequest**](UpdatePersonalityRequest.md)| |
### Return type
[**AgentProfileResponse**](AgentProfileResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | Successful Response | - |
**422** | Validation Error | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)

View file

@ -0,0 +1,33 @@
# AgentProfileResponse
Response model for agent profile.
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**agent_id** | **str** | |
**name** | **str** | |
**personality** | [**PersonalityTraits**](PersonalityTraits.md) | |
**background** | **str** | |
## Example
```python
from memora_client_api.models.agent_profile_response import AgentProfileResponse
# TODO update the JSON string below
json = "{}"
# create an instance of AgentProfileResponse from a JSON string
agent_profile_response_instance = AgentProfileResponse.from_json(json)
# print the JSON string representation of the object
print(AgentProfileResponse.to_json())
# convert the object into a dict
agent_profile_response_dict = agent_profile_response_instance.to_dict()
# create an instance of AgentProfileResponse from a dict
agent_profile_response_from_dict = AgentProfileResponse.from_dict(agent_profile_response_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View file

@ -0,0 +1,31 @@
# BackgroundResponse
Response model for background update.
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**background** | **str** | |
**personality** | [**PersonalityTraits**](PersonalityTraits.md) | | [optional]
## Example
```python
from memora_client_api.models.background_response import BackgroundResponse
# TODO update the JSON string below
json = "{}"
# create an instance of BackgroundResponse from a JSON string
background_response_instance = BackgroundResponse.from_json(json)
# print the JSON string representation of the object
print(BackgroundResponse.to_json())
# convert the object into a dict
background_response_dict = background_response_instance.to_dict()
# create an instance of BackgroundResponse from a dict
background_response_from_dict = BackgroundResponse.from_dict(background_response_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View file

@ -0,0 +1,35 @@
# BatchPutAsyncResponse
Response model for async batch put endpoint.
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**success** | **bool** | |
**message** | **str** | |
**agent_id** | **str** | |
**document_id** | **str** | | [optional]
**items_count** | **int** | |
**queued** | **bool** | |
## Example
```python
from memora_client_api.models.batch_put_async_response import BatchPutAsyncResponse
# TODO update the JSON string below
json = "{}"
# create an instance of BatchPutAsyncResponse from a JSON string
batch_put_async_response_instance = BatchPutAsyncResponse.from_json(json)
# print the JSON string representation of the object
print(BatchPutAsyncResponse.to_json())
# convert the object into a dict
batch_put_async_response_dict = batch_put_async_response_instance.to_dict()
# create an instance of BatchPutAsyncResponse from a dict
batch_put_async_response_from_dict = BatchPutAsyncResponse.from_dict(batch_put_async_response_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View file

@ -0,0 +1,31 @@
# BatchPutRequest
Request model for batch put endpoint.
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**items** | [**List[MemoryItem]**](MemoryItem.md) | |
**document_id** | **str** | | [optional]
## Example
```python
from memora_client_api.models.batch_put_request import BatchPutRequest
# TODO update the JSON string below
json = "{}"
# create an instance of BatchPutRequest from a JSON string
batch_put_request_instance = BatchPutRequest.from_json(json)
# print the JSON string representation of the object
print(BatchPutRequest.to_json())
# convert the object into a dict
batch_put_request_dict = batch_put_request_instance.to_dict()
# create an instance of BatchPutRequest from a dict
batch_put_request_from_dict = BatchPutRequest.from_dict(batch_put_request_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View file

@ -0,0 +1,34 @@
# BatchPutResponse
Response model for batch put endpoint.
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**success** | **bool** | |
**message** | **str** | |
**agent_id** | **str** | |
**document_id** | **str** | | [optional]
**items_count** | **int** | |
## Example
```python
from memora_client_api.models.batch_put_response import BatchPutResponse
# TODO update the JSON string below
json = "{}"
# create an instance of BatchPutResponse from a JSON string
batch_put_response_instance = BatchPutResponse.from_json(json)
# print the JSON string representation of the object
print(BatchPutResponse.to_json())
# convert the object into a dict
batch_put_response_dict = batch_put_response_instance.to_dict()
# create an instance of BatchPutResponse from a dict
batch_put_response_from_dict = BatchPutResponse.from_dict(batch_put_response_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View file

@ -0,0 +1,32 @@
# CreateAgentRequest
Request model for creating/updating an agent.
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**name** | **str** | | [optional]
**personality** | [**PersonalityTraits**](PersonalityTraits.md) | | [optional]
**background** | **str** | | [optional]
## Example
```python
from memora_client_api.models.create_agent_request import CreateAgentRequest
# TODO update the JSON string below
json = "{}"
# create an instance of CreateAgentRequest from a JSON string
create_agent_request_instance = CreateAgentRequest.from_json(json)
# print the JSON string representation of the object
print(CreateAgentRequest.to_json())
# convert the object into a dict
create_agent_request_dict = create_agent_request_instance.to_dict()
# create an instance of CreateAgentRequest from a dict
create_agent_request_from_dict = CreateAgentRequest.from_dict(create_agent_request_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View file

@ -0,0 +1,31 @@
# DeleteResponse
Response model for delete operations.
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**success** | **bool** | |
**message** | **str** | |
## Example
```python
from memora_client_api.models.delete_response import DeleteResponse
# TODO update the JSON string below
json = "{}"
# create an instance of DeleteResponse from a JSON string
delete_response_instance = DeleteResponse.from_json(json)
# print the JSON string representation of the object
print(DeleteResponse.to_json())
# convert the object into a dict
delete_response_dict = delete_response_instance.to_dict()
# create an instance of DeleteResponse from a dict
delete_response_from_dict = DeleteResponse.from_dict(delete_response_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View file

@ -0,0 +1,36 @@
# DocumentResponse
Response model for get document endpoint.
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **str** | |
**agent_id** | **str** | |
**original_text** | **str** | |
**content_hash** | **str** | |
**created_at** | **str** | |
**updated_at** | **str** | |
**memory_unit_count** | **int** | |
## Example
```python
from memora_client_api.models.document_response import DocumentResponse
# TODO update the JSON string below
json = "{}"
# create an instance of DocumentResponse from a JSON string
document_response_instance = DocumentResponse.from_json(json)
# print the JSON string representation of the object
print(DocumentResponse.to_json())
# convert the object into a dict
document_response_dict = document_response_instance.to_dict()
# create an instance of DocumentResponse from a dict
document_response_from_dict = DocumentResponse.from_dict(document_response_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View file

@ -0,0 +1,234 @@
# memora_client_api.DocumentsApi
All URIs are relative to *http://localhost*
Method | HTTP request | Description
------------- | ------------- | -------------
[**delete_document**](DocumentsApi.md#delete_document) | **DELETE** /api/v1/agents/{agent_id}/documents/{document_id} | Delete a document
[**get_document**](DocumentsApi.md#get_document) | **GET** /api/v1/agents/{agent_id}/documents/{document_id} | Get document details
[**list_documents**](DocumentsApi.md#list_documents) | **GET** /api/v1/agents/{agent_id}/documents | List documents
# **delete_document**
> object delete_document(agent_id, document_id)
Delete a document
Delete a document and all its associated memory units and links.
This will cascade delete:
- The document itself
- All memory units extracted from this document
- All links (temporal, semantic, entity) associated with those memory units
This operation cannot be undone.
### Example
```python
import memora_client_api
from memora_client_api.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost
# See configuration.py for a list of all supported configuration parameters.
configuration = memora_client_api.Configuration(
host = "http://localhost"
)
# Enter a context with an instance of the API client
async with memora_client_api.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = memora_client_api.DocumentsApi(api_client)
agent_id = 'agent_id_example' # str |
document_id = 'document_id_example' # str |
try:
# Delete a document
api_response = await api_instance.delete_document(agent_id, document_id)
print("The response of DocumentsApi->delete_document:\n")
pprint(api_response)
except Exception as e:
print("Exception when calling DocumentsApi->delete_document: %s\n" % e)
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**agent_id** | **str**| |
**document_id** | **str**| |
### Return type
**object**
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | Successful Response | - |
**422** | Validation Error | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **get_document**
> DocumentResponse get_document(agent_id, document_id)
Get document details
Get a specific document including its original text
### Example
```python
import memora_client_api
from memora_client_api.models.document_response import DocumentResponse
from memora_client_api.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost
# See configuration.py for a list of all supported configuration parameters.
configuration = memora_client_api.Configuration(
host = "http://localhost"
)
# Enter a context with an instance of the API client
async with memora_client_api.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = memora_client_api.DocumentsApi(api_client)
agent_id = 'agent_id_example' # str |
document_id = 'document_id_example' # str |
try:
# Get document details
api_response = await api_instance.get_document(agent_id, document_id)
print("The response of DocumentsApi->get_document:\n")
pprint(api_response)
except Exception as e:
print("Exception when calling DocumentsApi->get_document: %s\n" % e)
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**agent_id** | **str**| |
**document_id** | **str**| |
### Return type
[**DocumentResponse**](DocumentResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | Successful Response | - |
**422** | Validation Error | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **list_documents**
> ListDocumentsResponse list_documents(agent_id, q=q, limit=limit, offset=offset)
List documents
List documents with pagination and optional search. Documents are the source content from which memory units are extracted.
### Example
```python
import memora_client_api
from memora_client_api.models.list_documents_response import ListDocumentsResponse
from memora_client_api.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost
# See configuration.py for a list of all supported configuration parameters.
configuration = memora_client_api.Configuration(
host = "http://localhost"
)
# Enter a context with an instance of the API client
async with memora_client_api.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = memora_client_api.DocumentsApi(api_client)
agent_id = 'agent_id_example' # str |
q = 'q_example' # str | (optional)
limit = 100 # int | (optional) (default to 100)
offset = 0 # int | (optional) (default to 0)
try:
# List documents
api_response = await api_instance.list_documents(agent_id, q=q, limit=limit, offset=offset)
print("The response of DocumentsApi->list_documents:\n")
pprint(api_response)
except Exception as e:
print("Exception when calling DocumentsApi->list_documents: %s\n" % e)
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**agent_id** | **str**| |
**q** | **str**| | [optional]
**limit** | **int**| | [optional] [default to 100]
**offset** | **int**| | [optional] [default to 0]
### Return type
[**ListDocumentsResponse**](ListDocumentsResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | Successful Response | - |
**422** | Validation Error | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)

View file

@ -0,0 +1,33 @@
# GraphDataResponse
Response model for graph data endpoint.
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**nodes** | **List[Dict[str, object]]** | |
**edges** | **List[Dict[str, object]]** | |
**table_rows** | **List[Dict[str, object]]** | |
**total_units** | **int** | |
## Example
```python
from memora_client_api.models.graph_data_response import GraphDataResponse
# TODO update the JSON string below
json = "{}"
# create an instance of GraphDataResponse from a JSON string
graph_data_response_instance = GraphDataResponse.from_json(json)
# print the JSON string representation of the object
print(GraphDataResponse.to_json())
# convert the object into a dict
graph_data_response_dict = graph_data_response_instance.to_dict()
# create an instance of GraphDataResponse from a dict
graph_data_response_from_dict = GraphDataResponse.from_dict(graph_data_response_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View file

@ -0,0 +1,29 @@
# HTTPValidationError
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**detail** | [**List[ValidationError]**](ValidationError.md) | | [optional]
## Example
```python
from memora_client_api.models.http_validation_error import HTTPValidationError
# TODO update the JSON string below
json = "{}"
# create an instance of HTTPValidationError from a JSON string
http_validation_error_instance = HTTPValidationError.from_json(json)
# print the JSON string representation of the object
print(HTTPValidationError.to_json())
# convert the object into a dict
http_validation_error_dict = http_validation_error_instance.to_dict()
# create an instance of HTTPValidationError from a dict
http_validation_error_from_dict = HTTPValidationError.from_dict(http_validation_error_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View file

@ -0,0 +1,33 @@
# ListDocumentsResponse
Response model for list documents endpoint.
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**items** | **List[Dict[str, object]]** | |
**total** | **int** | |
**limit** | **int** | |
**offset** | **int** | |
## Example
```python
from memora_client_api.models.list_documents_response import ListDocumentsResponse
# TODO update the JSON string below
json = "{}"
# create an instance of ListDocumentsResponse from a JSON string
list_documents_response_instance = ListDocumentsResponse.from_json(json)
# print the JSON string representation of the object
print(ListDocumentsResponse.to_json())
# convert the object into a dict
list_documents_response_dict = list_documents_response_instance.to_dict()
# create an instance of ListDocumentsResponse from a dict
list_documents_response_from_dict = ListDocumentsResponse.from_dict(list_documents_response_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View file

@ -0,0 +1,33 @@
# ListMemoryUnitsResponse
Response model for list memory units endpoint.
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**items** | **List[Dict[str, object]]** | |
**total** | **int** | |
**limit** | **int** | |
**offset** | **int** | |
## Example
```python
from memora_client_api.models.list_memory_units_response import ListMemoryUnitsResponse
# TODO update the JSON string below
json = "{}"
# create an instance of ListMemoryUnitsResponse from a JSON string
list_memory_units_response_instance = ListMemoryUnitsResponse.from_json(json)
# print the JSON string representation of the object
print(ListMemoryUnitsResponse.to_json())
# convert the object into a dict
list_memory_units_response_dict = list_memory_units_response_instance.to_dict()
# create an instance of ListMemoryUnitsResponse from a dict
list_memory_units_response_from_dict = ListMemoryUnitsResponse.from_dict(list_memory_units_response_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View file

@ -0,0 +1,32 @@
# MemoryItem
Single memory item for batch put.
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**content** | **str** | |
**event_date** | **datetime** | | [optional]
**context** | **str** | | [optional]
## Example
```python
from memora_client_api.models.memory_item import MemoryItem
# TODO update the JSON string below
json = "{}"
# create an instance of MemoryItem from a JSON string
memory_item_instance = MemoryItem.from_json(json)
# print the JSON string representation of the object
print(MemoryItem.to_json())
# convert the object into a dict
memory_item_dict = memory_item_instance.to_dict()
# create an instance of MemoryItem from a dict
memory_item_from_dict = MemoryItem.from_dict(memory_item_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View file

@ -0,0 +1,556 @@
# memora_client_api.MemoryOperationsApi
All URIs are relative to *http://localhost*
Method | HTTP request | Description
------------- | ------------- | -------------
[**batch_put_async**](MemoryOperationsApi.md#batch_put_async) | **POST** /api/v1/agents/{agent_id}/memories/async | Store multiple memories asynchronously
[**batch_put_memories**](MemoryOperationsApi.md#batch_put_memories) | **POST** /api/v1/agents/{agent_id}/memories | Store multiple memories
[**cancel_operation**](MemoryOperationsApi.md#cancel_operation) | **DELETE** /api/v1/agents/{agent_id}/operations/{operation_id} | Cancel a pending async operation
[**delete_memory_unit**](MemoryOperationsApi.md#delete_memory_unit) | **DELETE** /api/v1/agents/{agent_id}/memories/{unit_id} | Delete a memory unit
[**list_memories**](MemoryOperationsApi.md#list_memories) | **GET** /api/v1/agents/{agent_id}/memories/list | List memory units
[**list_operations**](MemoryOperationsApi.md#list_operations) | **GET** /api/v1/agents/{agent_id}/operations | List async operations
[**search_memories**](MemoryOperationsApi.md#search_memories) | **POST** /api/v1/agents/{agent_id}/memories/search | Search memory
# **batch_put_async**
> BatchPutAsyncResponse batch_put_async(agent_id, batch_put_request)
Store multiple memories asynchronously
Store multiple memory items in batch asynchronously using the task backend.
This endpoint returns immediately after queuing the task, without waiting for completion.
The actual processing happens in the background.
Features:
- Immediate response (non-blocking)
- Background processing via task queue
- Efficient batch processing
- Automatic fact extraction from natural language
- Entity recognition and linking
- Document tracking with automatic upsert (when document_id is provided)
- Temporal and semantic linking
The system automatically:
1. Queues the batch put task
2. Returns immediately with success=True, queued=True
3. Processes in background: extracts facts, generates embeddings, creates links
Note: If document_id is provided and already exists, the old document and its memory units will be deleted before creating new ones (upsert behavior).
### Example
```python
import memora_client_api
from memora_client_api.models.batch_put_async_response import BatchPutAsyncResponse
from memora_client_api.models.batch_put_request import BatchPutRequest
from memora_client_api.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost
# See configuration.py for a list of all supported configuration parameters.
configuration = memora_client_api.Configuration(
host = "http://localhost"
)
# Enter a context with an instance of the API client
async with memora_client_api.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = memora_client_api.MemoryOperationsApi(api_client)
agent_id = 'agent_id_example' # str |
batch_put_request = memora_client_api.BatchPutRequest() # BatchPutRequest |
try:
# Store multiple memories asynchronously
api_response = await api_instance.batch_put_async(agent_id, batch_put_request)
print("The response of MemoryOperationsApi->batch_put_async:\n")
pprint(api_response)
except Exception as e:
print("Exception when calling MemoryOperationsApi->batch_put_async: %s\n" % e)
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**agent_id** | **str**| |
**batch_put_request** | [**BatchPutRequest**](BatchPutRequest.md)| |
### Return type
[**BatchPutAsyncResponse**](BatchPutAsyncResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | Successful Response | - |
**422** | Validation Error | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **batch_put_memories**
> BatchPutResponse batch_put_memories(agent_id, batch_put_request)
Store multiple memories
Store multiple memory items in batch with automatic fact extraction.
Features:
- Efficient batch processing
- Automatic fact extraction from natural language
- Entity recognition and linking
- Document tracking with automatic upsert (when document_id is provided)
- Temporal and semantic linking
The system automatically:
1. Extracts semantic facts from the content
2. Generates embeddings
3. Deduplicates similar facts
4. Creates temporal, semantic, and entity links
5. Tracks document metadata
Note: If document_id is provided and already exists, the old document and its memory units will be deleted before creating new ones (upsert behavior).
### Example
```python
import memora_client_api
from memora_client_api.models.batch_put_request import BatchPutRequest
from memora_client_api.models.batch_put_response import BatchPutResponse
from memora_client_api.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost
# See configuration.py for a list of all supported configuration parameters.
configuration = memora_client_api.Configuration(
host = "http://localhost"
)
# Enter a context with an instance of the API client
async with memora_client_api.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = memora_client_api.MemoryOperationsApi(api_client)
agent_id = 'agent_id_example' # str |
batch_put_request = memora_client_api.BatchPutRequest() # BatchPutRequest |
try:
# Store multiple memories
api_response = await api_instance.batch_put_memories(agent_id, batch_put_request)
print("The response of MemoryOperationsApi->batch_put_memories:\n")
pprint(api_response)
except Exception as e:
print("Exception when calling MemoryOperationsApi->batch_put_memories: %s\n" % e)
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**agent_id** | **str**| |
**batch_put_request** | [**BatchPutRequest**](BatchPutRequest.md)| |
### Return type
[**BatchPutResponse**](BatchPutResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | Successful Response | - |
**422** | Validation Error | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **cancel_operation**
> object cancel_operation(agent_id, operation_id)
Cancel a pending async operation
Cancel a pending async operation by removing it from the queue
### Example
```python
import memora_client_api
from memora_client_api.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost
# See configuration.py for a list of all supported configuration parameters.
configuration = memora_client_api.Configuration(
host = "http://localhost"
)
# Enter a context with an instance of the API client
async with memora_client_api.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = memora_client_api.MemoryOperationsApi(api_client)
agent_id = 'agent_id_example' # str |
operation_id = 'operation_id_example' # str |
try:
# Cancel a pending async operation
api_response = await api_instance.cancel_operation(agent_id, operation_id)
print("The response of MemoryOperationsApi->cancel_operation:\n")
pprint(api_response)
except Exception as e:
print("Exception when calling MemoryOperationsApi->cancel_operation: %s\n" % e)
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**agent_id** | **str**| |
**operation_id** | **str**| |
### Return type
**object**
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | Successful Response | - |
**422** | Validation Error | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **delete_memory_unit**
> object delete_memory_unit(agent_id, unit_id)
Delete a memory unit
Delete a single memory unit and all its associated links (temporal, semantic, and entity links)
### Example
```python
import memora_client_api
from memora_client_api.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost
# See configuration.py for a list of all supported configuration parameters.
configuration = memora_client_api.Configuration(
host = "http://localhost"
)
# Enter a context with an instance of the API client
async with memora_client_api.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = memora_client_api.MemoryOperationsApi(api_client)
agent_id = 'agent_id_example' # str |
unit_id = 'unit_id_example' # str |
try:
# Delete a memory unit
api_response = await api_instance.delete_memory_unit(agent_id, unit_id)
print("The response of MemoryOperationsApi->delete_memory_unit:\n")
pprint(api_response)
except Exception as e:
print("Exception when calling MemoryOperationsApi->delete_memory_unit: %s\n" % e)
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**agent_id** | **str**| |
**unit_id** | **str**| |
### Return type
**object**
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | Successful Response | - |
**422** | Validation Error | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **list_memories**
> ListMemoryUnitsResponse list_memories(agent_id, fact_type=fact_type, q=q, limit=limit, offset=offset)
List memory units
List memory units with pagination and optional full-text search. Supports filtering by fact_type.
### Example
```python
import memora_client_api
from memora_client_api.models.list_memory_units_response import ListMemoryUnitsResponse
from memora_client_api.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost
# See configuration.py for a list of all supported configuration parameters.
configuration = memora_client_api.Configuration(
host = "http://localhost"
)
# Enter a context with an instance of the API client
async with memora_client_api.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = memora_client_api.MemoryOperationsApi(api_client)
agent_id = 'agent_id_example' # str |
fact_type = 'fact_type_example' # str | (optional)
q = 'q_example' # str | (optional)
limit = 100 # int | (optional) (default to 100)
offset = 0 # int | (optional) (default to 0)
try:
# List memory units
api_response = await api_instance.list_memories(agent_id, fact_type=fact_type, q=q, limit=limit, offset=offset)
print("The response of MemoryOperationsApi->list_memories:\n")
pprint(api_response)
except Exception as e:
print("Exception when calling MemoryOperationsApi->list_memories: %s\n" % e)
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**agent_id** | **str**| |
**fact_type** | **str**| | [optional]
**q** | **str**| | [optional]
**limit** | **int**| | [optional] [default to 100]
**offset** | **int**| | [optional] [default to 0]
### Return type
[**ListMemoryUnitsResponse**](ListMemoryUnitsResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | Successful Response | - |
**422** | Validation Error | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **list_operations**
> object list_operations(agent_id)
List async operations
Get a list of all async operations (pending and failed) for a specific agent, including error messages for failed operations
### Example
```python
import memora_client_api
from memora_client_api.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost
# See configuration.py for a list of all supported configuration parameters.
configuration = memora_client_api.Configuration(
host = "http://localhost"
)
# Enter a context with an instance of the API client
async with memora_client_api.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = memora_client_api.MemoryOperationsApi(api_client)
agent_id = 'agent_id_example' # str |
try:
# List async operations
api_response = await api_instance.list_operations(agent_id)
print("The response of MemoryOperationsApi->list_operations:\n")
pprint(api_response)
except Exception as e:
print("Exception when calling MemoryOperationsApi->list_operations: %s\n" % e)
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**agent_id** | **str**| |
### Return type
**object**
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | Successful Response | - |
**422** | Validation Error | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **search_memories**
> SearchResponse search_memories(agent_id, search_request)
Search memory
Search memory using semantic similarity and spreading activation.
The fact_type parameter is optional and must be one of:
- 'world': General knowledge about people, places, events, and things that happen
- 'agent': Memories about what the AI agent did, actions taken, and tasks performed
- 'opinion': The agent's formed beliefs, perspectives, and viewpoints
### Example
```python
import memora_client_api
from memora_client_api.models.search_request import SearchRequest
from memora_client_api.models.search_response import SearchResponse
from memora_client_api.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost
# See configuration.py for a list of all supported configuration parameters.
configuration = memora_client_api.Configuration(
host = "http://localhost"
)
# Enter a context with an instance of the API client
async with memora_client_api.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = memora_client_api.MemoryOperationsApi(api_client)
agent_id = 'agent_id_example' # str |
search_request = memora_client_api.SearchRequest() # SearchRequest |
try:
# Search memory
api_response = await api_instance.search_memories(agent_id, search_request)
print("The response of MemoryOperationsApi->search_memories:\n")
pprint(api_response)
except Exception as e:
print("Exception when calling MemoryOperationsApi->search_memories: %s\n" % e)
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**agent_id** | **str**| |
**search_request** | [**SearchRequest**](SearchRequest.md)| |
### Return type
[**SearchResponse**](SearchResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | Successful Response | - |
**422** | Validation Error | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)

View file

@ -0,0 +1,35 @@
# PersonalityTraits
Personality traits based on Big Five model.
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**openness** | **float** | Openness to experience (0-1) |
**conscientiousness** | **float** | Conscientiousness (0-1) |
**extraversion** | **float** | Extraversion (0-1) |
**agreeableness** | **float** | Agreeableness (0-1) |
**neuroticism** | **float** | Neuroticism (0-1) |
**bias_strength** | **float** | How strongly personality influences opinions (0-1) |
## Example
```python
from memora_client_api.models.personality_traits import PersonalityTraits
# TODO update the JSON string below
json = "{}"
# create an instance of PersonalityTraits from a JSON string
personality_traits_instance = PersonalityTraits.from_json(json)
# print the JSON string representation of the object
print(PersonalityTraits.to_json())
# convert the object into a dict
personality_traits_dict = personality_traits_instance.to_dict()
# create an instance of PersonalityTraits from a dict
personality_traits_from_dict = PersonalityTraits.from_dict(personality_traits_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View file

@ -0,0 +1,89 @@
# memora_client_api.ReasoningApi
All URIs are relative to *http://localhost*
Method | HTTP request | Description
------------- | ------------- | -------------
[**think**](ReasoningApi.md#think) | **POST** /api/v1/agents/{agent_id}/think | Think and generate answer
# **think**
> ThinkResponse think(agent_id, think_request)
Think and generate answer
Think and formulate an answer using agent identity, world facts, and opinions.
This endpoint:
1. Retrieves agent facts (agent's identity)
2. Retrieves world facts relevant to the query
3. Retrieves existing opinions (agent's perspectives)
4. Uses LLM to formulate a contextual answer
5. Extracts and stores any new opinions formed
6. Returns plain text answer, the facts used, and new opinions
### Example
```python
import memora_client_api
from memora_client_api.models.think_request import ThinkRequest
from memora_client_api.models.think_response import ThinkResponse
from memora_client_api.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost
# See configuration.py for a list of all supported configuration parameters.
configuration = memora_client_api.Configuration(
host = "http://localhost"
)
# Enter a context with an instance of the API client
async with memora_client_api.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = memora_client_api.ReasoningApi(api_client)
agent_id = 'agent_id_example' # str |
think_request = memora_client_api.ThinkRequest() # ThinkRequest |
try:
# Think and generate answer
api_response = await api_instance.think(agent_id, think_request)
print("The response of ReasoningApi->think:\n")
pprint(api_response)
except Exception as e:
print("Exception when calling ReasoningApi->think: %s\n" % e)
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**agent_id** | **str**| |
**think_request** | [**ThinkRequest**](ThinkRequest.md)| |
### Return type
[**ThinkResponse**](ThinkResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | Successful Response | - |
**422** | Validation Error | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)

View file

@ -0,0 +1,35 @@
# SearchRequest
Request model for search endpoint.
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**query** | **str** | |
**fact_type** | **List[str]** | | [optional]
**thinking_budget** | **int** | | [optional] [default to 100]
**max_tokens** | **int** | | [optional] [default to 4096]
**trace** | **bool** | | [optional] [default to False]
**question_date** | **str** | | [optional]
## Example
```python
from memora_client_api.models.search_request import SearchRequest
# TODO update the JSON string below
json = "{}"
# create an instance of SearchRequest from a JSON string
search_request_instance = SearchRequest.from_json(json)
# print the JSON string representation of the object
print(SearchRequest.to_json())
# convert the object into a dict
search_request_dict = search_request_instance.to_dict()
# create an instance of SearchRequest from a dict
search_request_from_dict = SearchRequest.from_dict(search_request_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View file

@ -0,0 +1,31 @@
# SearchResponse
Response model for search endpoints.
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**results** | [**List[SearchResult]**](SearchResult.md) | |
**trace** | **Dict[str, object]** | | [optional]
## Example
```python
from memora_client_api.models.search_response import SearchResponse
# TODO update the JSON string below
json = "{}"
# create an instance of SearchResponse from a JSON string
search_response_instance = SearchResponse.from_json(json)
# print the JSON string representation of the object
print(SearchResponse.to_json())
# convert the object into a dict
search_response_dict = search_response_instance.to_dict()
# create an instance of SearchResponse from a dict
search_response_from_dict = SearchResponse.from_dict(search_response_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

Some files were not shown because too many files have changed in this diff Show more