Skip to content

Commit

Permalink
Fixed deserialized computed fields issue (#233)
Browse files Browse the repository at this point in the history
  • Loading branch information
whitead authored Jan 30, 2024
1 parent f60a79f commit 1cd866b
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 3 deletions.
18 changes: 16 additions & 2 deletions paperqa/types.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
from typing import Any, Callable
from uuid import UUID, uuid4

from pydantic import BaseModel, ConfigDict, Field, computed_field, field_validator
from pydantic import (
BaseModel,
ConfigDict,
Field,
computed_field,
field_validator,
model_validator,
)

from .prompts import (
citation_prompt,
Expand Down Expand Up @@ -169,12 +176,19 @@ class Answer(BaseModel):
cost: float | None = None
# key is model name, value is (prompt, completion) token counts
token_counts: dict[str, list[int]] = Field(default_factory=dict)
model_config = ConfigDict(extra="forbid")
model_config = ConfigDict(extra="ignore")

def __str__(self) -> str:
"""Return the answer as a string."""
return self.formatted_answer

@model_validator(mode="before")
@classmethod
def remove_computed(cls, data: Any) -> Any:
if isinstance(data, dict):
data.pop("used_contexts", None)
return data

@computed_field # type: ignore
@property
def used_contexts(self) -> set[str]:
Expand Down
2 changes: 1 addition & 1 deletion paperqa/version.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "4.0.0-pre.6"
__version__ = "4.0.0-pre.7"
4 changes: 4 additions & 0 deletions tests/test_paperqa.py
Original file line number Diff line number Diff line change
Expand Up @@ -552,6 +552,10 @@ def test_answer_attributes():
js = answer.model_dump_json()
assert "used_contexts" in js

# make sure it can be deserialized
answer2 = Answer.model_validate_json(js)
assert answer2.used_contexts == used_citations


def test_llmresult_callbacks():
my_results = []
Expand Down

0 comments on commit 1cd866b

Please sign in to comment.