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.

test_async.py 6.6 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. #!/usr/bin/env python3 -m pytest
  2. import asyncio
  3. import os
  4. import sys
  5. import pytest
  6. from test_assistant_agent import KEY_LOC, OAI_CONFIG_LIST
  7. import autogen
  8. sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
  9. from conftest import skip_openai # noqa: E402
  10. try:
  11. from openai import OpenAI
  12. except ImportError:
  13. skip = True
  14. else:
  15. skip = False or skip_openai
  16. def get_market_news(ind, ind_upper):
  17. data = {
  18. "feed": [
  19. {
  20. "title": "Palantir CEO Says Our Generation's Atomic Bomb Could Be AI Weapon - And Arrive Sooner Than You Think - Palantir Technologies ( NYSE:PLTR ) ",
  21. "summary": "Christopher Nolan's blockbuster movie \"Oppenheimer\" has reignited the public discourse surrounding the United States' use of an atomic bomb on Japan at the end of World War II.",
  22. "overall_sentiment_score": 0.009687,
  23. },
  24. {
  25. "title": '3 "Hedge Fund Hotels" Pulling into Support',
  26. "summary": "Institutional quality stocks have several benefits including high-liquidity, low beta, and a long runway. Strategist Andrew Rocco breaks down what investors should look for and pitches 3 ideas.",
  27. "banner_image": "https://staticx-tuner.zacks.com/images/articles/main/92/87.jpg",
  28. "overall_sentiment_score": 0.219747,
  29. },
  30. {
  31. "title": "PDFgear, Bringing a Completely-Free PDF Text Editing Feature",
  32. "summary": "LOS ANGELES, July 26, 2023 /PRNewswire/ -- PDFgear, a leading provider of PDF solutions, announced a piece of exciting news for everyone who works extensively with PDF documents.",
  33. "overall_sentiment_score": 0.360071,
  34. },
  35. {
  36. "title": "Researchers Pitch 'Immunizing' Images Against Deepfake Manipulation",
  37. "summary": "A team at MIT says injecting tiny disruptive bits of code can cause distorted deepfake images.",
  38. "overall_sentiment_score": -0.026894,
  39. },
  40. {
  41. "title": "Nvidia wins again - plus two more takeaways from this week's mega-cap earnings",
  42. "summary": "We made some key conclusions combing through quarterly results for Microsoft and Alphabet and listening to their conference calls with investors.",
  43. "overall_sentiment_score": 0.235177,
  44. },
  45. ]
  46. }
  47. feeds = data["feed"][ind:ind_upper]
  48. feeds_summary = "\n".join(
  49. [
  50. f"News summary: {f['title']}. {f['summary']} overall_sentiment_score: {f['overall_sentiment_score']}"
  51. for f in feeds
  52. ]
  53. )
  54. return feeds_summary
  55. @pytest.mark.skipif(skip, reason="openai not installed OR requested to skip")
  56. @pytest.mark.asyncio
  57. async def test_async_groupchat():
  58. config_list = autogen.config_list_from_json(OAI_CONFIG_LIST, KEY_LOC)
  59. llm_config = {
  60. "timeout": 600,
  61. "cache_seed": 41,
  62. "config_list": config_list,
  63. "temperature": 0,
  64. }
  65. # create an AssistantAgent instance named "assistant"
  66. assistant = autogen.AssistantAgent(
  67. name="assistant",
  68. llm_config={
  69. "timeout": 600,
  70. "cache_seed": 41,
  71. "config_list": config_list,
  72. "temperature": 0,
  73. },
  74. system_message="You are a helpful assistant. Reply 'TERMINATE' to end the conversation.",
  75. )
  76. # create a UserProxyAgent instance named "user"
  77. user_proxy = autogen.UserProxyAgent(
  78. name="user",
  79. human_input_mode="NEVER",
  80. max_consecutive_auto_reply=5,
  81. code_execution_config=False,
  82. default_auto_reply=None,
  83. )
  84. groupchat = autogen.GroupChat(agents=[user_proxy, assistant], messages=[], max_round=12)
  85. manager = autogen.GroupChatManager(
  86. groupchat=groupchat,
  87. llm_config=llm_config,
  88. is_termination_msg=lambda x: "TERMINATE" in x.get("content", ""),
  89. )
  90. await user_proxy.a_initiate_chat(manager, message="""Have a short conversation with the assistant.""")
  91. assert len(user_proxy.chat_messages) > 0
  92. @pytest.mark.skipif(skip, reason="openai not installed OR requested to skip")
  93. @pytest.mark.asyncio
  94. async def test_stream():
  95. config_list = autogen.config_list_from_json(OAI_CONFIG_LIST, KEY_LOC)
  96. data = asyncio.Future()
  97. async def add_stock_price_data():
  98. # simulating the data stream
  99. for i in range(0, 2, 1):
  100. latest_news = get_market_news(i, i + 1)
  101. if data.done():
  102. data.result().append(latest_news)
  103. else:
  104. data.set_result([latest_news])
  105. # print(data.result())
  106. await asyncio.sleep(5)
  107. data_task = asyncio.create_task(add_stock_price_data())
  108. # create an AssistantAgent instance named "assistant"
  109. assistant = autogen.AssistantAgent(
  110. name="assistant",
  111. llm_config={
  112. "timeout": 600,
  113. "cache_seed": 41,
  114. "config_list": config_list,
  115. "temperature": 0,
  116. },
  117. system_message="You are a financial expert.",
  118. )
  119. # create a UserProxyAgent instance named "user"
  120. user_proxy = autogen.UserProxyAgent(
  121. name="user",
  122. human_input_mode="NEVER",
  123. max_consecutive_auto_reply=5,
  124. code_execution_config=False,
  125. default_auto_reply=None,
  126. )
  127. async def add_data_reply(recipient, messages, sender, config):
  128. await asyncio.sleep(0.1)
  129. data = config["news_stream"]
  130. if data.done():
  131. result = data.result()
  132. if result:
  133. news_str = "\n".join(result)
  134. result.clear()
  135. return (
  136. True,
  137. f"Just got some latest market news. Merge your new suggestion with previous ones.\n{news_str}",
  138. )
  139. return False, None
  140. user_proxy.register_reply(autogen.AssistantAgent, add_data_reply, position=2, config={"news_stream": data})
  141. chat_res = await user_proxy.a_initiate_chat(
  142. assistant, message="""Give me investment suggestion in 3 bullet points.""", summary_method="reflection_with_llm"
  143. )
  144. print("Chat summary:", chat_res.summary)
  145. print("Chat cost:", chat_res.cost)
  146. while not data_task.done() and not data_task.cancelled():
  147. reply = await user_proxy.a_generate_reply(sender=assistant)
  148. if reply is not None:
  149. res = await user_proxy.a_send(reply, assistant)
  150. print("Chat summary and cost:", res.summary, res.cost)
  151. if __name__ == "__main__":
  152. asyncio.run(test_stream())