Skip to content

Conversation

@rayrayraykk
Copy link
Member

@rayrayraykk rayrayraykk commented Nov 27, 2025

Usage:

import os
from agentscope.agent import ReActAgent
from agentscope.model import DashScopeChatModel
from agentscope.formatter import DashScopeChatFormatter
from agentscope.tool import Toolkit, execute_python_code
from agentscope.pipeline import stream_printing_messages

from agentscope_runtime.engine import AgentApp
from agentscope_runtime.engine.schemas.agent_schemas import AgentRequest
from agentscope_runtime.adapters.agentscope.memory import (
    AgentScopeSessionHistoryMemory,
)
from agentscope_runtime.engine.services.agent_state import (
    InMemoryStateService,
)
from agentscope_runtime.engine.services.session_history import (
    InMemorySessionHistoryService,
)

PORT = 8090


def run_app():
    """Start AgentApp with streaming output enabled."""
    agent_app = AgentApp(
        app_name="Friday",
        app_description="A helpful assistant",
    )

    @agent_app.init
    async def init_func(self):
        self.state_service = InMemoryStateService()
        self.session_service = InMemorySessionHistoryService()

        await self.state_service.start()
        await self.session_service.start()

    @agent_app.shutdown
    async def shutdown_func(self):
        await self.state_service.stop()
        await self.session_service.stop()

    @agent_app.query(framework="agentscope")
    async def query_func(
        self,
        msgs,
        request: AgentRequest = None,
        **kwargs,
    ):
        session_id = request.session_id
        user_id = request.user_id

        state = await self.state_service.export_state(
            session_id=session_id,
            user_id=user_id,
        )

        toolkit = Toolkit()
        toolkit.register_tool_function(execute_python_code)

        agent = ReActAgent(
            name="Friday",
            model=DashScopeChatModel(
                "qwen-turbo",
                api_key=os.getenv("DASHSCOPE_API_KEY"),
                enable_thinking=True,
                stream=True,
            ),
            sys_prompt="You're a helpful assistant named Friday.",
            toolkit=toolkit,
            memory=AgentScopeSessionHistoryMemory(
                service=self.session_service,
                session_id=session_id,
                user_id=user_id,
            ),
            formatter=DashScopeChatFormatter(),
        )

        if state:
            agent.load_state_dict(state)

        async for msg, last in stream_printing_messages(
            agents=[agent],
            coroutine_task=agent(msgs),
        ):
            yield msg, last

        state = agent.state_dict()

        await self.state_service.save_state(
            user_id=user_id,
            session_id=session_id,
            state=state,
        )

    agent_app.run(host="127.0.0.1", port=PORT, web_ui=True)

if __name__ == "__main__":
    run_app()

@rayrayraykk rayrayraykk changed the title Support lanuch webui by agentapp Support lanuch webui by agentapp.run(web_ui=True) Nov 27, 2025
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR adds support for launching a browser-based WebUI alongside the AgentApp HTTP API server. When the new web_ui=True parameter is passed to the run() method, the application spawns a separate Node.js-based WebUI process using npx @agentscope-ai/chat.

Key Changes:

  • Added web_ui parameter to the run() method to optionally launch the WebUI
  • Integrated subprocess management to start the WebUI alongside the FastAPI server
  • Enhanced documentation with detailed parameter descriptions and usage notes

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

"[AgentApp] Note: First WebUI launch may take extra time "
"as dependencies are installed.",
)
with subprocess.Popen(shlex.split(cmd)):
Copy link

Copilot AI Nov 27, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's no error handling for the WebUI subprocess startup. If npx is not installed or the WebUI package fails to start, the subprocess will fail silently and only the uvicorn server will run. Consider checking if the subprocess starts successfully before proceeding with uvicorn.run(), or at least logging any subprocess errors.

Suggested change
with subprocess.Popen(shlex.split(cmd)):
try:
webui_proc = subprocess.Popen(shlex.split(cmd))
except Exception as e:
logger.error(f"[AgentApp] Failed to start WebUI subprocess: {e}")
else:
# Optionally, wait a short time and check if process exited
import time
time.sleep(2)
if webui_proc.poll() is not None:
logger.error(f"[AgentApp] WebUI subprocess exited early with code {webui_proc.returncode}")

Copilot uses AI. Check for mistakes.
self,
host="0.0.0.0",
port=8090,
web_ui=False,
Copy link

Copilot AI Nov 27, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new web_ui parameter lacks test coverage. The existing tests in tests/integrated/test_agent_app.py only test the basic run() method without the web_ui=True option. Consider adding test coverage for the WebUI launch functionality, including:

  1. Testing that the WebUI subprocess starts when web_ui=True
  2. Testing cleanup of the WebUI subprocess on shutdown
  3. Testing error handling when npx is not available

Copilot uses AI. Check for mistakes.
@AgentScopeTeam AgentScopeTeam merged commit fd43626 into agentscope-ai:dev Nov 28, 2025
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants