You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

app_agent.py 3.5 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. import json
  2. import os
  3. from typing import Any
  4. import aiofiles
  5. import yaml
  6. from autogen_agentchat.agents import AssistantAgent
  7. from autogen_agentchat.messages import TextMessage
  8. from autogen_core import CancellationToken
  9. from autogen_core.models import ChatCompletionClient
  10. from fastapi import FastAPI, HTTPException
  11. from fastapi.middleware.cors import CORSMiddleware
  12. from fastapi.responses import FileResponse
  13. from fastapi.staticfiles import StaticFiles
  14. app = FastAPI()
  15. # Add CORS middleware
  16. app.add_middleware(
  17. CORSMiddleware,
  18. allow_origins=["*"], # Allows all origins
  19. allow_credentials=True,
  20. allow_methods=["*"], # Allows all methods
  21. allow_headers=["*"], # Allows all headers
  22. )
  23. # Serve static files
  24. app.mount("/static", StaticFiles(directory="."), name="static")
  25. @app.get("/")
  26. async def root():
  27. """Serve the chat interface HTML file."""
  28. return FileResponse("app_agent.html")
  29. model_config_path = "model_config.yaml"
  30. state_path = "agent_state.json"
  31. history_path = "agent_history.json"
  32. async def get_agent() -> AssistantAgent:
  33. """Get the assistant agent, load state from file."""
  34. # Get model client from config.
  35. async with aiofiles.open(model_config_path, "r") as file:
  36. model_config = yaml.safe_load(await file.read())
  37. model_client = ChatCompletionClient.load_component(model_config)
  38. # Create the assistant agent.
  39. agent = AssistantAgent(
  40. name="assistant",
  41. model_client=model_client,
  42. system_message="You are a helpful assistant.",
  43. )
  44. # Load state from file.
  45. if not os.path.exists(state_path):
  46. return agent # Return agent without loading state.
  47. async with aiofiles.open(state_path, "r") as file:
  48. state = json.loads(await file.read())
  49. await agent.load_state(state)
  50. return agent
  51. async def get_history() -> list[dict[str, Any]]:
  52. """Get chat history from file."""
  53. if not os.path.exists(history_path):
  54. return []
  55. async with aiofiles.open(history_path, "r") as file:
  56. return json.loads(await file.read())
  57. @app.get("/history")
  58. async def history() -> list[dict[str, Any]]:
  59. try:
  60. return await get_history()
  61. except Exception as e:
  62. raise HTTPException(status_code=500, detail=str(e)) from e
  63. @app.post("/chat", response_model=TextMessage)
  64. async def chat(request: TextMessage) -> TextMessage:
  65. try:
  66. # Get the agent and respond to the message.
  67. agent = await get_agent()
  68. response = await agent.on_messages(messages=[request], cancellation_token=CancellationToken())
  69. # Save agent state to file.
  70. state = await agent.save_state()
  71. async with aiofiles.open(state_path, "w") as file:
  72. await file.write(json.dumps(state))
  73. # Save chat history to file.
  74. history = await get_history()
  75. history.append(request.model_dump())
  76. history.append(response.chat_message.model_dump())
  77. async with aiofiles.open(history_path, "w") as file:
  78. await file.write(json.dumps(history))
  79. assert isinstance(response.chat_message, TextMessage)
  80. return response.chat_message
  81. except Exception as e:
  82. error_message = {
  83. "type": "error",
  84. "content": f"Error: {str(e)}",
  85. "source": "system"
  86. }
  87. raise HTTPException(status_code=500, detail=error_message) from e
  88. # Example usage
  89. if __name__ == "__main__":
  90. import uvicorn
  91. uvicorn.run(app, host="0.0.0.0", port=8001)