Skip to content

Commit

Permalink
support session creation (#19)
Browse files Browse the repository at this point in the history
* fix(ui): remove unused code

* feat(ui): support session creatiion. fix some args error in api calling
  • Loading branch information
BroKun authored Aug 5, 2024
1 parent af71dab commit 59d5bbd
Show file tree
Hide file tree
Showing 11 changed files with 74 additions and 32 deletions.
12 changes: 6 additions & 6 deletions packages/magent_ui/src/magent_ui/routers/agents/router.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import enum
from typing import List
from fastapi import APIRouter, HTTPException
from fastapi import APIRouter
from agentuniverse_product.service.agent_service.agent_service import AgentService
from agentuniverse_product.service.model.agent_dto import AgentDTO
from pydantic import BaseModel
Expand Down Expand Up @@ -37,17 +37,17 @@ class MessageCreate(BaseModel):


class MessageOutput(BaseModel):
message_id: str
message_id: int
session_id: str
message: str
response_time: str
output: dict
response_time: float
output: str
start_time: str
end_time: str


@router.put("/agents/{agent_id}/chat", response_model=MessageOutput)
@router.post("/agents/{agent_id}/chat", response_model=MessageOutput)
async def chat(agent_id, model: MessageCreate):
output_dict = AgentService.chat(
model.agent_id, model.session_id, model.input)
print(output_dict)
return MessageOutput.model_validate(output_dict)
12 changes: 9 additions & 3 deletions packages/magent_ui/src/magent_ui/routers/sessions/router.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from typing import List
from fastapi import APIRouter, HTTPException
from fastapi import APIRouter
from agentuniverse_product.service.session_service.session_service import SessionService
from agentuniverse_product.service.model.session_dto import SessionDTO
from pydantic import BaseModel

router = APIRouter()
sessions_router = router
Expand All @@ -17,9 +18,14 @@ async def get_session_detail(session_id):
return SessionService.get_session_detail(session_id)


class SessionCreate(BaseModel):
agent_id: str


@router.post("/sessions", response_model=SessionDTO)
async def create_session(agent_id):
return SessionService.create_session(agent_id)
async def create_session(model: SessionCreate):
session_id = SessionService.create_session(model.agent_id)
return SessionService.get_session_detail(session_id)


@router.delete("/sessions/{session_id}", response_model=str)
Expand Down
4 changes: 4 additions & 0 deletions web/ui/src/common/async-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ export abstract class AsyncModel<T = any, O = any> {
ready: Promise<T>;
protected readyDeferred: Deferred<T> = new Deferred<T>();

constructor() {
this.ready = this.readyDeferred.promise;
}

initialize(option: O) {
if (this.shouldInitFromMeta(option)) {
this.fromMeta(option);
Expand Down
2 changes: 1 addition & 1 deletion web/ui/src/modules/agent/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ export const AgentModelType = {
return !!(data && 'id' in data);
},
isFullOption(data?: Record<string, any>): boolean {
return AgentModelType.isOption(data) && 'name' in data && 'avatar' in data;
return AgentModelType.isOption(data) && 'nickname' in data;
},
};

Expand Down
8 changes: 6 additions & 2 deletions web/ui/src/modules/chat-message/chat-message-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export class ChatMessageModel {
agentId: string;
sessionId: string;
@prop()
messages: MessageItem[];
messages: MessageItem[] = [];
@prop()
created?: Dayjs;

Expand Down Expand Up @@ -53,7 +53,11 @@ export class ChatMessageModel {
this.sending = true;
const res = await this.axios.post<MessageOption>(
`/api/v1/agents/${option.agentId}/chat`,
option,
{
agent_id: option.agentId,
session_id: option.sessionId,
input: option.input,
},
);
if (res.data.id) {
this.updateMeta(res.data);
Expand Down
4 changes: 3 additions & 1 deletion web/ui/src/modules/session/session-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@ export class SessionManager {
};

createSession = async (option: SessionCreate): Promise<SessionOption> => {
const res = await this.axios.post<APISession>(`/api/v1/session`, option);
const res = await this.axios.post<APISession>(`/api/v1/sessions`, {
agent_id: option.agentId,
});
if (!res.data.id) {
throw new Error('Create session failed');
}
Expand Down
26 changes: 23 additions & 3 deletions web/ui/src/views/agent-dev/chat-view.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { useMatch } from 'react-router-dom';

import { AgentManager } from '../../modules/agent/agent-manager.js';
import type { AgentModel } from '../../modules/agent/protocol.js';
import type { SessionOption } from '../../modules/session/protocol.js';
import type { SessionModel } from '../../modules/session/protocol.js';
import { ChatView } from '../chat/view.js';
import { SessionsView } from '../sessions/view.js';

Expand Down Expand Up @@ -74,7 +74,9 @@ export class AgentView extends BaseView {
const agent = this.agentManager.getOrCreateAgent({ id: this.agentId });
agent.fetchInfo();
this.agent = agent;
return agent;
}
return undefined;
};

protected initSessionView = async () => {
Expand All @@ -87,12 +89,30 @@ export class AgentView extends BaseView {
this.sessions = sessions;
};

protected getAgentTitleName = async (agent: AgentModel) => {
if (agent.name) {
return agent.name;
} else {
await agent.ready;
return agent.name;
}
};
protected updateTitle = async (agent: AgentModel) => {
const title = await this.getAgentTitleName(agent);
if (title) {
document.title = title;
}
};

override onViewMount(): void {
this.initAgent();
const agent = this.initAgent();
if (agent) {
this.updateTitle(agent);
}
this.initSessionView();
}

openChat = async (session: SessionOption) => {
openChat = async (session: SessionModel) => {
const chatView = await this.viewManager.getOrCreateView(ChatView, {
agentId: session.agentId,
sessionId: session.id,
Expand Down
22 changes: 11 additions & 11 deletions web/ui/src/views/chat/components/message/message.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,18 +44,18 @@ export const Message = (props: MessageProps) => {
}

let content: ReactNode = message.content;
if (!exchange.sending) {
content = (
<>
{message.content}
<Typing />
</>
);
if (exchange.sending) {
if (!content) {
content = <LoadingOutlined />;
} else {
content = (
<>
{message.content}
<Typing />
</>
);
}
}
if (!content) {
content = <LoadingOutlined />;
}

return (
<div className="chat-message">
<div className="chat-message-box">
Expand Down
4 changes: 1 addition & 3 deletions web/ui/src/views/chat/view.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import { ClearOutlined, VerticalAlignBottomOutlined } from '@ant-design/icons';
import type { Syringe } from '@difizen/mana-app';
import { ObservableContext } from '@difizen/mana-app';
import {
BaseView,
Deferred,
Expand Down Expand Up @@ -153,7 +151,7 @@ export class ChatView extends BaseView {
}
const msg: MessageCreate = {
agentId: this.agentId,
sessionId: this.id,
sessionId: this.sessionId,
input: msgContent,
};
this.session?.chat(msg);
Expand Down
3 changes: 1 addition & 2 deletions web/ui/src/views/protal-layout/view.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const PortalLayoutComponent = forwardRef<HTMLDivElement>(
function PortalLayoutComponent(props, ref) {
const instance = useInject<PortalLayoutView>(ViewInstance);
const match = useMatch('/portal/:portal');
const portal = match.params?.portal;
const portal = match?.params?.portal;
const navigate = useNavigate();

document.title = `magent-ui ${portal}`;
Expand All @@ -40,7 +40,6 @@ const PortalLayoutComponent = forwardRef<HTMLDivElement>(
options={segemntPortals}
value={portal}
onChange={(value) => {
history.push();
navigate(`/portal/${value}`, { replace: true });
}}
/>
Expand Down
9 changes: 9 additions & 0 deletions web/ui/src/views/sessions/view.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
transient,
ViewOption,
} from '@difizen/mana-app';
import { Button } from 'antd';
import { forwardRef } from 'react';

import type { SessionModel } from '../../modules/session/index.js';
Expand All @@ -27,6 +28,7 @@ const SessionsViewComponent = forwardRef<HTMLDivElement>(
{session.id}
</div>
))}
<Button onClick={instance.createSession}>开启新会话</Button>
</div>
);
},
Expand Down Expand Up @@ -73,4 +75,11 @@ export class SessionsView extends BaseView {
selectSession = (session: SessionModel) => {
this.active = session;
};

createSession = async () => {
const opt = await this.sessionManager.createSession({ agentId: this.agentId });
const session = this.sessionManager.getOrCreateSession(opt);
this.sessions.unshift(session);
this.active = session;
};
}

0 comments on commit 59d5bbd

Please sign in to comment.