react_data_analysis.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. """A data analysis example implemented by assistant"""
  2. import os
  3. from pprint import pprint
  4. from typing import Optional
  5. from qwen_agent.agents import ReActChat
  6. from qwen_agent.gui import WebUI
  7. ROOT_RESOURCE = os.path.join(os.path.dirname(__file__), 'resource')
  8. def init_agent_service():
  9. llm_cfg = {
  10. 'model': 'qwen2-instruct',
  11. 'model_server': 'http://lq.lianqiai.cn:20335/v1',
  12. 'api_key': "",
  13. # 'model': 'qwen-max',
  14. # 'model_server': 'dashscope',
  15. # 'api_key': os.getenv('DASHSCOPE_API_KEY'),
  16. }
  17. tools = ['code_interpreter']
  18. bot = ReActChat(llm=llm_cfg,
  19. name='code interpreter',
  20. description='This agent can run code to solve the problem',
  21. function_list=tools)
  22. return bot
  23. def test(query: str = 'pd.head the file first and then help me draw a line chart to show the changes in stock prices',
  24. file: Optional[str] = os.path.join(ROOT_RESOURCE, 'stock_prices.csv')):
  25. # Define the agent
  26. bot = init_agent_service()
  27. # Chat
  28. messages = []
  29. if not file:
  30. messages.append({'role': 'user', 'content': query})
  31. else:
  32. messages.append({'role': 'user', 'content': [{'text': query}, {'file': file}]})
  33. for response in bot.run(messages):
  34. pprint(response, indent=2)
  35. def app_tui():
  36. # Define the agent
  37. bot = init_agent_service()
  38. # Chat
  39. messages = []
  40. while True:
  41. # Query example: pd.head the file first and then help me draw a line chart to show the changes in stock prices
  42. query = input('user question: ')
  43. # File example: resource/stock_prices.csv
  44. file = input('file url (press enter if no file): ').strip()
  45. if not query:
  46. print('user question cannot be empty!')
  47. continue
  48. if not file:
  49. messages.append({'role': 'user', 'content': query})
  50. else:
  51. messages.append({'role': 'user', 'content': [{'text': query}, {'file': file}]})
  52. response = []
  53. for response in bot.run(messages):
  54. print('bot response:', response)
  55. messages.extend(response)
  56. def app_gui():
  57. bot = init_agent_service()
  58. chatbot_config = {
  59. 'prompt.suggestions': [{
  60. 'text': 'pd.head the file first and then help me draw a line chart to show the changes in stock prices',
  61. 'files': [os.path.join(ROOT_RESOURCE, 'stock_prices.csv')]
  62. }, 'Draw a line graph y=x^2']
  63. }
  64. WebUI(bot, chatbot_config=chatbot_config).run()
  65. if __name__ == '__main__':
  66. # test()
  67. # app_tui()
  68. app_gui()