-
Notifications
You must be signed in to change notification settings - Fork 5
feat(quick-start): persist agent conversations #837
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
xyh202131
wants to merge
1
commit into
1024XEngineer:main
Choose a base branch
from
xyh202131:feat/quick-start-conversation-storage
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
5 changes: 5 additions & 0 deletions
5
backend/packages/app/src/windup_app/server/quick_start_conversation/__init__.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| """Quick Start Agent 对话持久化。""" | ||
|
|
||
| from .model import QuickStartAgentConversation | ||
|
|
||
| __all__ = ["QuickStartAgentConversation"] |
40 changes: 40 additions & 0 deletions
40
backend/packages/app/src/windup_app/server/quick_start_conversation/model.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| """Quick Start Agent 对话侧车模型。""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from datetime import datetime, timezone | ||
|
|
||
| from sqlalchemy import BigInteger, DateTime, ForeignKey, Integer, JSON | ||
| from sqlalchemy.dialects.postgresql import JSONB | ||
| from sqlalchemy.orm import Mapped, mapped_column | ||
|
|
||
| from windup_framework.db import Base | ||
|
|
||
|
|
||
| class QuickStartAgentConversation(Base): | ||
| """与 WorkflowRun 一对一的 Agent 对话快照。""" | ||
|
|
||
| __tablename__ = "windup_quick_start_agent_conversation" | ||
|
|
||
| workflow_run_id: Mapped[int] = mapped_column( | ||
| BigInteger, | ||
| ForeignKey("windup_workflow_run.id", ondelete="CASCADE"), | ||
| primary_key=True, | ||
| ) | ||
| turns: Mapped[list[dict]] = mapped_column( | ||
| JSON().with_variant(JSONB, "postgresql"), | ||
| nullable=False, | ||
| default=list, | ||
| ) | ||
| schema_version: Mapped[int] = mapped_column(Integer, nullable=False, default=2) | ||
| version: Mapped[int] = mapped_column(Integer, nullable=False, default=1) | ||
| created_at: Mapped[datetime] = mapped_column( | ||
| DateTime(timezone=True), | ||
| nullable=False, | ||
| default=lambda: datetime.now(timezone.utc), | ||
| ) | ||
| updated_at: Mapped[datetime] = mapped_column( | ||
| DateTime(timezone=True), | ||
| nullable=False, | ||
| default=lambda: datetime.now(timezone.utc), | ||
| ) | ||
99 changes: 99 additions & 0 deletions
99
backend/packages/app/src/windup_app/server/quick_start_conversation/service.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,99 @@ | ||
| """Quick Start Agent 对话快照的 SQLAlchemy 服务。""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from datetime import datetime, timezone | ||
|
|
||
| from sqlalchemy import update | ||
| from sqlalchemy.exc import IntegrityError | ||
| from sqlalchemy.orm import Session | ||
|
|
||
| from windup_common.enums.biz_code import BizCode | ||
| from windup_common.exceptions import BizException | ||
|
|
||
| from .model import QuickStartAgentConversation | ||
|
|
||
|
|
||
| def _version_conflict() -> None: | ||
| raise BizException( | ||
| "Agent 对话版本冲突,请刷新后重试", | ||
| code=BizCode.CONFLICT, | ||
| ) | ||
|
|
||
|
|
||
| class QuickStartConversationService: | ||
| """读取和乐观锁写入每条 WorkflowRun 的完整对话快照。""" | ||
|
|
||
| def get( | ||
| self, | ||
| session: Session, | ||
| workflow_run_id: int, | ||
| ) -> QuickStartAgentConversation | None: | ||
| return session.get(QuickStartAgentConversation, workflow_run_id) | ||
|
|
||
| def save( | ||
| self, | ||
| session: Session, | ||
| workflow_run_id: int, | ||
| *, | ||
| expected_version: int, | ||
| schema_version: int, | ||
| turns: list[dict], | ||
| ) -> QuickStartAgentConversation: | ||
| conversation = self.get(session, workflow_run_id) | ||
| if conversation is None: | ||
| if expected_version != 0: | ||
| _version_conflict() | ||
| candidate = QuickStartAgentConversation( | ||
| workflow_run_id=workflow_run_id, | ||
| turns=turns, | ||
| schema_version=schema_version, | ||
| ) | ||
| try: | ||
| # 两个首次 PUT 可同时读到空记录;savepoint 只回滚输掉的 INSERT, | ||
| # 不破坏外层请求事务,随后按幂等规则读取胜出的快照。 | ||
| with session.begin_nested(): | ||
| session.add(candidate) | ||
| session.flush() | ||
| return candidate | ||
| except IntegrityError: | ||
| session.expire_all() | ||
| conversation = self.get(session, workflow_run_id) | ||
| if conversation is None: | ||
| raise | ||
| if ( | ||
| conversation.turns == turns | ||
| and conversation.schema_version == schema_version | ||
| ): | ||
| return conversation | ||
| _version_conflict() | ||
|
|
||
| if ( | ||
| conversation.turns == turns | ||
| and conversation.schema_version == schema_version | ||
| ): | ||
| return conversation | ||
| if conversation.version != expected_version: | ||
| _version_conflict() | ||
|
|
||
| result = session.execute( | ||
| update(QuickStartAgentConversation) | ||
| .where( | ||
| QuickStartAgentConversation.workflow_run_id == workflow_run_id, | ||
| QuickStartAgentConversation.version == expected_version, | ||
| ) | ||
| .values( | ||
| turns=turns, | ||
| schema_version=schema_version, | ||
| version=expected_version + 1, | ||
| updated_at=datetime.now(timezone.utc), | ||
| ) | ||
| .execution_options(synchronize_session="fetch") | ||
| ) | ||
| if result.rowcount == 0: | ||
| _version_conflict() | ||
| session.refresh(conversation) | ||
| return conversation | ||
|
|
||
|
|
||
| service = QuickStartConversationService() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| from unittest.mock import MagicMock, Mock | ||
|
|
||
| from sqlalchemy.exc import IntegrityError | ||
| from sqlalchemy.orm import Session | ||
|
|
||
| from windup_app.server.quick_start_conversation.model import QuickStartAgentConversation | ||
| from windup_app.server.quick_start_conversation.service import ( | ||
| QuickStartConversationService, | ||
| ) | ||
|
|
||
|
|
||
| def test_concurrent_first_insert_returns_the_identical_winning_snapshot(): | ||
| turns = [{"role": "user", "content": "像素骑士"}] | ||
| winner = QuickStartAgentConversation( | ||
| workflow_run_id=18, | ||
| turns=turns, | ||
| schema_version=2, | ||
| version=1, | ||
| ) | ||
| session = MagicMock(spec=Session) | ||
| session.flush.side_effect = IntegrityError("duplicate", {}, Exception("unique")) | ||
| service = QuickStartConversationService() | ||
| service.get = Mock(side_effect=[None, winner]) | ||
|
|
||
| saved = service.save( | ||
| session, | ||
| 18, | ||
| expected_version=0, | ||
| schema_version=2, | ||
| turns=turns, | ||
| ) | ||
|
|
||
| assert saved is winner | ||
| session.expire_all.assert_called_once_with() |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
但关键是,有这个会话记录存在对应的表单,后续你要如何治理。你想清楚一点。比如用户想要在几天前的对话记录在新加记录,你要如何加?