Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 32 additions & 7 deletions atomic-agents/atomic_agents/context/chat_history.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import uuid
from copy import deepcopy
from enum import Enum
from importlib import import_module
from pathlib import Path
from typing import Dict, List, Optional, Tuple, Type, Union

Expand Down Expand Up @@ -271,10 +272,15 @@ def dump(self) -> str:
serialized_history = []
for message in self.history:
content_class = message.content.__class__
class_name = content_class.__qualname__
# A function-local class may be explicitly exported under its simple
# name. Preserve that existing convention; <locals> is not importable.
if "<locals>" in class_name:
class_name = content_class.__name__
serialized_message = {
"role": message.role,
"content": {
"class_name": f"{content_class.__module__}.{content_class.__name__}",
"class_name": f"{content_class.__module__}.{class_name}",
"data": message.content.model_dump_json(round_trip=True),
},
"turn_id": message.turn_id,
Expand Down Expand Up @@ -348,12 +354,31 @@ def _get_class_from_string(class_string: str) -> Type[BaseIOSchema]:
Raises:
AttributeError: If the class cannot be found.
"""
module_name, class_name = class_string.rsplit(".", 1)
module = __import__(module_name, fromlist=[class_name])
content_class = getattr(module, class_name)
if not isinstance(content_class, type) or not issubclass(content_class, BaseIOSchema):
raise ValueError(f"Invalid serialized data: {class_string} is not a BaseIOSchema subclass")
return content_class
parts = class_string.split(".")
import_error = None
for boundary in range(len(parts) - 1, 0, -1):
module_name = ".".join(parts[:boundary])
try:
obj = import_module(module_name)
except ModuleNotFoundError as error:
# Only shorten a missing module path. A missing dependency inside
# an existing schema module must retain its original exception.
if error.name != module_name and not module_name.startswith(f"{error.name}."):
raise
if import_error is None:
import_error = error
continue
obj = getattr(obj, parts[boundary])
for name in parts[boundary + 1 :]:
if not isinstance(obj, type):
raise ValueError(f"Invalid serialized data: {class_string} traverses a non-class attribute")
obj = getattr(obj, name)
if not isinstance(obj, type) or not issubclass(obj, BaseIOSchema):
raise ValueError(f"Invalid serialized data: {class_string} is not a BaseIOSchema subclass")
return obj
if import_error is not None:
raise import_error
raise ValueError(f"Expected a fully qualified schema class name: {class_string}")

def _process_multimodal_paths(self, obj):
"""
Expand Down
180 changes: 180 additions & 0 deletions atomic-agents/tests/context/test_nested_schema_history.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
"""History persistence retains importable nested schema identities."""

import importlib
import json
import sys
from types import SimpleNamespace

import pytest
from pydantic import Json

from atomic_agents import BaseIOSchema
from atomic_agents.context import ChatHistory


class Content(BaseIOSchema):
"""A top-level schema sharing the nested schemas' simple class name."""

text: str


class First:
class Content(BaseIOSchema):
"""Content owned by the first component."""

text: str


class Second:
class Content(BaseIOSchema):
"""Content owned by the second component."""

text: str


class Deep:
class Inner:
class Content(BaseIOSchema):
"""Content nested more than one level deep."""

text: str


class NonSchema:
value = object()

class Content:
pass


class Typed:
class Content(BaseIOSchema):
"""A nested schema requiring round-trip JSON serialization."""

values: Json[list[int]]


@pytest.mark.parametrize("schema", [Content, First.Content, Second.Content, Deep.Inner.Content])
def test_round_trip_preserves_exact_schema_class(schema):
original = ChatHistory(max_messages=4)
original.add_message("user", schema(text="saved conversation"))
saved = original.dump()
restored = ChatHistory()
restored.load(saved)

assert type(restored.history[0].content) is schema
assert restored.get_history() == original.get_history()
assert restored.current_turn_id == original.current_turn_id
assert restored.max_messages == 4
assert json.loads(saved)["history"][0]["content"]["class_name"] == f"{schema.__module__}.{schema.__qualname__}"


def test_nested_schema_module_can_be_reimported_after_saving(tmp_path, monkeypatch):
module_name = "nested_history_fixture"
(tmp_path / f"{module_name}.py").write_text(
"from atomic_agents import BaseIOSchema\n"
"class Component:\n"
" class Message(BaseIOSchema):\n"
' """A durable component message."""\n'
" text: str\n"
)
monkeypatch.syspath_prepend(str(tmp_path))
try:
module = importlib.import_module(module_name)
original = ChatHistory()
original.add_message("assistant", module.Component.Message(text="persisted"))
saved = original.dump()
del sys.modules[module_name]

restored = ChatHistory()
restored.load(saved)
reloaded = importlib.import_module(module_name)
assert type(restored.history[0].content) is reloaded.Component.Message
assert restored.history[0].content.text == "persisted"
finally:
sys.modules.pop(module_name, None)


def test_exported_local_schema_keeps_legacy_path(monkeypatch):
class ExportedContent(BaseIOSchema):
"""A local schema explicitly exported by its defining module."""

text: str

monkeypatch.setattr(sys.modules[__name__], "ExportedContent", ExportedContent, raising=False)
original = ChatHistory()
original.add_message("user", ExportedContent(text="legacy export"))
saved = original.dump()
restored = ChatHistory()
restored.load(saved)

assert type(restored.history[0].content) is ExportedContent
assert json.loads(saved)["history"][0]["content"]["class_name"] == f"{__name__}.ExportedContent"


def test_missing_nested_class_keeps_existing_history():
history = ChatHistory()
history.add_message("user", Content(text="keep me"))
original = history.dump()
broken = json.loads(original)
broken["history"][0]["content"]["class_name"] = f"{__name__}.First.Missing"

with pytest.raises(ValueError, match="Invalid serialized data"):
history.load(json.dumps(broken))
assert history.dump() == original


def test_schema_module_dependency_failure_is_not_hidden(tmp_path, monkeypatch):
(tmp_path / "broken_history_fixture.py").write_text("import missing_history_dependency\n")
monkeypatch.syspath_prepend(str(tmp_path))
with pytest.raises(ModuleNotFoundError) as error:
ChatHistory._get_class_from_string("broken_history_fixture.Component.Message")
assert error.value.name == "missing_history_dependency"


@pytest.mark.parametrize("name", ["NonSchema.value", "NonSchema.Content"])
def test_nested_non_schema_objects_cannot_replace_existing_history(name):
history = ChatHistory()
history.add_message("user", Content(text="keep me"))
original = history.dump()
broken = json.loads(original)
broken["history"][0]["content"]["class_name"] = f"{__name__}.{name}"

with pytest.raises(ValueError, match="is not a BaseIOSchema subclass"):
history.load(json.dumps(broken))
assert history.dump() == original


@pytest.mark.parametrize("nested", [False, True], ids=["module-attribute", "class-attribute"])
@pytest.mark.parametrize("dynamic", [False, True], ids=["stored-attribute", "dynamic-attribute"])
def test_loading_does_not_traverse_non_class_objects(monkeypatch, nested, dynamic):
visited = []

class DynamicNamespace:
def __getattr__(self, name):
visited.append(name)
return Content

namespace = DynamicNamespace() if dynamic else SimpleNamespace(Content=Content)
parent = First if nested else sys.modules[__name__]
monkeypatch.setattr(parent, "namespace", namespace, raising=False)
path = f"{__name__}." + ("First." if nested else "") + "namespace.Content"
history = ChatHistory()
history.add_message("user", Content(text="keep me"))
original = history.dump()
broken = json.loads(original)
broken["history"][0]["content"]["class_name"] = path

with pytest.raises(ValueError, match="Invalid serialized data"):
history.load(json.dumps(broken))
assert visited == []
assert history.dump() == original


def test_nested_schema_preserves_round_trip_json_fields():
original = ChatHistory()
original.add_message("user", Typed.Content(values="[1, 2, 3]"))
restored = ChatHistory()
restored.load(original.dump())
assert type(restored.history[0].content) is Typed.Content
assert restored.history[0].content.values == [1, 2, 3]
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,10 @@ class WebpageScraperToolConfig(BaseToolConfig):

timeout: int = 30
headers: Dict[str, str] = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3",
"User-Agent": (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"
),
"Accept": "text/html,application/xhtml+xml,application/xml",
"Accept-Language": "en-US,en;q=0.9",
}
Expand Down Expand Up @@ -113,18 +116,25 @@ def _fetch_webpage(self, url: str) -> tuple[str, str]:
Returns:
tuple[str, str]: The HTML content and final response URL.
"""
response = requests.get(url, headers=self.headers, timeout=self.timeout)

if len(response.content) > self.config.max_content_length:
raise ValueError(f"Content length exceeds maximum of {self.config.max_content_length} bytes")

content_type = Message()
content_type["Content-Type"] = response.headers.get("Content-Type", "")
charset = content_type.get_content_charset()
# Decode HTML from its bytes: a BOM, an explicit HTTP charset, and an
# HTML declaration take precedence over heuristic encoding detection.
decoded = UnicodeDammit(response.content, is_html=True, user_encodings=[charset] if charset else []).unicode_markup
return (decoded if decoded is not None else response.text), response.url
response = requests.get(url, headers=self.headers, timeout=self.timeout, stream=True)
try:
response.raise_for_status()
body = bytearray()
for chunk in response.iter_content(chunk_size=8192):
if len(body) + len(chunk) > self.config.max_content_length:
raise ValueError(f"Content length exceeds maximum of {self.config.max_content_length} bytes")
body.extend(chunk)

content_type = Message()
content_type["Content-Type"] = response.headers.get("Content-Type", "")
charset = content_type.get_content_charset()
# Decode the bounded body using the same BOM, HTTP charset, HTML
# declaration, and heuristic precedence as a complete response.
content = bytes(body)
decoded = UnicodeDammit(content, is_html=True, user_encodings=[charset] if charset else []).unicode_markup
return (decoded if decoded is not None else content.decode("utf-8", errors="replace")), response.url
finally:
response.close()

@staticmethod
def _resolve_content_urls(soup: BeautifulSoup, document_url: str) -> None:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -153,8 +153,11 @@ def fetch_video_metadata(self, video_id: str) -> VideoMetadata:
"""
api_key = os.getenv("YOUTUBE_API_KEY")
youtube = build("youtube", "v3", developerKey=api_key)
request = youtube.videos().list(part="snippet", id=video_id)
response = request.execute()
try:
request = youtube.videos().list(part="snippet", id=video_id)
response = request.execute()
finally:
youtube.close()

if not response["items"]:
raise Exception(f"No metadata found for video '{video_id}'")
Expand All @@ -164,7 +167,7 @@ def fetch_video_metadata(self, video_id: str) -> VideoMetadata:
id=video_id,
title=video_info["title"],
channel=video_info["channelTitle"],
published_at=datetime.fromisoformat(video_info["publishedAt"].rstrip("Z")),
published_at=datetime.fromisoformat(video_info["publishedAt"]),
)


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,8 +150,11 @@ def fetch_video_metadata(self, video_id: str) -> VideoMetadata:
"""
api_key = os.getenv("YOUTUBE_API_KEY")
youtube = build("youtube", "v3", developerKey=api_key)
request = youtube.videos().list(part="snippet", id=video_id)
response = request.execute()
try:
request = youtube.videos().list(part="snippet", id=video_id)
response = request.execute()
finally:
youtube.close()

if not response["items"]:
raise Exception(f"No metadata found for video '{video_id}'")
Expand All @@ -161,7 +164,7 @@ def fetch_video_metadata(self, video_id: str) -> VideoMetadata:
id=video_id,
title=video_info["title"],
channel=video_info["channelTitle"],
published_at=datetime.fromisoformat(video_info["publishedAt"].rstrip("Z")),
published_at=datetime.fromisoformat(video_info["publishedAt"]),
)


Expand Down
21 changes: 20 additions & 1 deletion atomic-forge/tools/pdf_reader/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,13 @@ Extracts text and metadata from a PDF, given either a local file path or an HTTP
- `source` (str): a local file path or HTTP(S) URL pointing at a PDF.
- `page_range` (str, optional): `'1'`, `'1-5'`, `'1,3,5-7'`, etc. (1-based). Out-of-range pages are silently skipped.
- `include_metadata` (bool): default `True`.
- `extraction_mode` (`"plain"` or `"layout"`): defaults to `"plain"`. Choose `"layout"` to preserve rendered row and column positions with fixed-width spacing, useful for reports and tables whose PDF text operators are stored column by column.
- `include_links` (bool): extract embedded URI annotations for the selected pages; default `False`.

### Output Schema
- `source` (str): echo of the input source.
- `text` (str): concatenated text for the extracted pages, separated by `\f` (form feed).
- `pages` (list[PdfPage]): per-page extracted text with 1-based `page_number`.
- `pages` (list[PdfPage]): per-page extracted text with 1-based `page_number` and `links` (list[str]). Links are empty unless requested.
- `page_count` (int): number of pages extracted (after page_range filter).
- `total_page_count` (int): total pages in the source document.
- `metadata` (PdfMetadata, optional): document info dictionary.
Expand All @@ -46,12 +48,29 @@ print(out.text[:1000])

# Read a local PDF, every page
out = tool.run(PdfReaderToolInputSchema(source="./paper.pdf"))

# Preserve row associations in a text-based inventory report
out = tool.run(PdfReaderToolInputSchema(
source="./inventory.pdf",
extraction_mode="layout",
))
```

To keep citation targets that are not printed as text:

```python
out = tool.run(PdfReaderToolInputSchema(source="./paper.pdf", include_links=True))
for page in out.pages:
print(page.page_number, page.links)
```

URI targets are returned as stored in the PDF, in annotation order, including repeated and relative targets. Internal page jumps and other annotation types are omitted. Targets are never fetched or executed, and extracted page text stays unchanged.

## Notes
- The tool fails gracefully and returns `error` set in the output rather than raising.
- For URL sources, the download is hard-capped by `max_size_bytes` in the config (default 50 MB).
- Encrypted PDFs are not currently supported.
- Layout extraction uses [pypdf's layout mode](https://pypdf.readthedocs.io/en/5.1.0/user/extract-text.html). It retains spacing in the returned text; it does not produce structured table cells or perform OCR. Complex layouts and rotated text have the same limitations as the underlying pypdf mode.

## Contributing
PRs welcome — see the main repo `CONTRIBUTING.md`.
Expand Down
Loading
Loading