Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

UserProxyAgent fails to install packages #239

Closed
schoenia opened this issue Oct 14, 2023 · 8 comments
Closed

UserProxyAgent fails to install packages #239

schoenia opened this issue Oct 14, 2023 · 8 comments

Comments

@schoenia
Copy link

schoenia commented Oct 14, 2023

Hi!

for some reason I'm unable to get this to work:

my code looks like the following:

import autogen

config_list = [
{
'model': 'gpt-4',
'api_key': 'x',
}, # OpenAI API endpoint for gpt-4
{
'model': 'gpt-3.5-turbo',
'api_key': 'x',
}, # OpenAI API endpoint for gpt-3.5-turbo
{
'model': 'gpt-3.5-turbo-16k',
'api_key': 'x',
}, # OpenAI API endpoint for gpt-3.5-turbo-16k
]

create an AssistantAgent named "assistant"

assistant = autogen.AssistantAgent(
name="assistant",
llm_config={
"seed": 42, # seed for caching and reproducibility
"config_list": config_list, # a list of OpenAI API configurations
"temperature": 0, # temperature for sampling
}, # configuration for autogen's enhanced inference API which is compatible with OpenAI API
)

create a UserProxyAgent instance named "user_proxy"

user_proxy = autogen.UserProxyAgent(
name="user_proxy",
human_input_mode="NEVER",
max_consecutive_auto_reply=10,
is_termination_msg=lambda x: x.get("content", "").rstrip().endswith("TERMINATE"),
code_execution_config={
"work_dir": "coding",
"use_docker": False, # set to True or image name like "python:3" to use docker
},
)

the assistant receives a message from the user_proxy, which contains the task description

user_proxy.initiate_chat(
assistant,
message="""What date is today? Compare the year-to-date gain for META and TESLA.""",
)

followup of the previous question

user_proxy.send(
recipient=assistant,
message="""Plot a chart of their stock price change YTD and save to stock_price_ytd.png.""",
)

output is the following:

`C:\autogen\venv2\venv\Scripts\python.exe C:\autogen\venv2\main.py
user_proxy (to assistant):

What date is today? Compare the year-to-date gain for META and TESLA.


assistant (to user_proxy):

First, let's get the current date using Python.

# python code
from datetime import date

# Get today's date
today = date.today()

print("Today's date:", today)

Next, we need to fetch the stock prices for META (Facebook) and TESLA for the current year. We can use the yfinance library in Python to fetch this data. If yfinance is not installed, it can be installed using pip: pip install yfinance.

Here is the Python code to fetch the stock prices and calculate the year-to-date gain:

# python code
import yfinance as yf
from datetime import datetime

# Get the current year
current_year = datetime.now().year

# Download stock data from the start of the year to today
meta_data = yf.download('FB', start=f'{current_year}-01-01', end=today)
tesla_data = yf.download('TSLA', start=f'{current_year}-01-01', end=today)

# Calculate the year-to-date gain for each stock
meta_ytd_gain = ((meta_data['Close'][-1] - meta_data['Close'][0]) / meta_data['Close'][0]) * 100
tesla_ytd_gain = ((tesla_data['Close'][-1] - tesla_data['Close'][0]) / tesla_data['Close'][0]) * 100

print(f'META year-to-date gain: {meta_ytd_gain}%')
print(f'TESLA year-to-date gain: {tesla_ytd_gain}%')

This code will print the year-to-date gain for both META and TESLA.


EXECUTING CODE BLOCK 0 (inferred language is python)...
SIGALRM is not supported on Windows. No timeout will be enforced.

EXECUTING CODE BLOCK 1 (inferred language is python)...
SIGALRM is not supported on Windows. No timeout will be enforced.
user_proxy (to assistant):

exitcode: 1 (execution failed)
Code output:
Today's date: 2023-10-14

Traceback (most recent call last):
File "", line 9, in
meta_data = yf.download('FB', start=f'{current_year}-01-01', end=today)
^^^^^
NameError: name 'today' is not defined


SIGALRM is not supported on Windows. No timeout will be enforced.
assistant (to user_proxy):

I apologize for the oversight. The variable today was defined in the first code block but not in the second one. Let's correct this by defining today in the second code block as well. Here's the corrected code:

# python code
import yfinance as yf
from datetime import datetime, date

# Get the current year and today's date
current_year = datetime.now().year
today = date.today()

# Download stock data from the start of the year to today
meta_data = yf.download('FB', start=f'{current_year}-01-01', end=today)
tesla_data = yf.download('TSLA', start=f'{current_year}-01-01', end=today)

# Calculate the year-to-date gain for each stock
meta_ytd_gain = ((meta_data['Close'][-1] - meta_data['Close'][0]) / meta_data['Close'][0]) * 100
tesla_ytd_gain = ((tesla_data['Close'][-1] - tesla_data['Close'][0]) / tesla_data['Close'][0]) * 100

print(f'META year-to-date gain: {meta_ytd_gain}%')
print(f'TESLA year-to-date gain: {tesla_ytd_gain}%')

This code will print the year-to-date gain for both META and TESLA.


EXECUTING CODE BLOCK 0 (inferred language is python)...
user_proxy (to assistant):

exitcode: 1 (execution failed)
Code output:

1 Failed download:
['FB']: Exception('%ticker%: No timezone found, symbol may be delisted')
:14: FutureWarning: Series.getitem treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use ser.iloc[pos]
meta_ytd_gain = ((meta_data['Close'][-1] - meta_data['Close'][0]) / meta_data['Close'][0]) * 100
Traceback (most recent call last):
File "", line 14, in
meta_ytd_gain = ((meta_data['Close'][-1] - meta_data['Close'][0]) / meta_data['Close'][0]) * 100
~~~~~~~~~~~~~~~~~~^^^^
File "C:\autogen\venv2\venv\Lib\site-packages\pandas\core\series.py", line 1037, in getitem
return self._values[key]
~~~~~~~~~~~~^^^^^
IndexError: index -1 is out of bounds for axis 0 with size 0


SIGALRM is not supported on Windows. No timeout will be enforced.
assistant (to user_proxy):

I apologize for the confusion. The ticker symbol for Meta Platforms (formerly Facebook) has changed from 'FB' to 'META'. Let's correct this in the code:

# python code
import yfinance as yf
from datetime import datetime, date

# Get the current year and today's date
current_year = datetime.now().year
today = date.today()

# Download stock data from the start of the year to today
meta_data = yf.download('META', start=f'{current_year}-01-01', end=today)
tesla_data = yf.download('TSLA', start=f'{current_year}-01-01', end=today)

# Calculate the year-to-date gain for each stock
meta_ytd_gain = ((meta_data['Close'][-1] - meta_data['Close'][0]) / meta_data['Close'][0]) * 100
tesla_ytd_gain = ((tesla_data['Close'][-1] - tesla_data['Close'][0]) / tesla_data['Close'][0]) * 100

print(f'META year-to-date gain: {meta_ytd_gain}%')
print(f'TESLA year-to-date gain: {tesla_ytd_gain}%')

This code will print the year-to-date gain for both META and TESLA.


EXECUTING CODE BLOCK 0 (inferred language is python)...
user_proxy (to assistant):

exitcode: 0 (execution succeeded)
Code output:

[100%%*] 1 of 1 completed

[100%%*] 1 of 1 completed
META year-to-date gain: 152.27674188762134%
TESLA year-to-date gain: 132.3034215188311%


assistant (to user_proxy):

Great! The code executed successfully.

As of today (October 14, 2023), the year-to-date gain for META is approximately 152.28%, and for TESLA, it's approximately 132.30%.

This means that if you had invested in these stocks at the beginning of the year, your investment in META would have increased by about 152.28% and in TESLA by about 132.30%.

Please note that stock prices are subject to market fluctuations and the values provided are based on the closing prices of the stocks on the given date.

TERMINATE


user_proxy (to assistant):

Plot a chart of their stock price change YTD and save to stock_price_ytd.png.


SIGALRM is not supported on Windows. No timeout will be enforced.
assistant (to user_proxy):

Sure, we can use the matplotlib library in Python to plot the stock price changes for META and TESLA. If matplotlib is not installed, it can be installed using pip: pip install matplotlib.

Here is the Python code to plot the stock prices and save the plot to a file:

# python code
import matplotlib.pyplot as plt

# Plot the closing prices of META and TESLA
plt.figure(figsize=(14, 7))
plt.plot(meta_data['Close'], label='META')
plt.plot(tesla_data['Close'], label='TESLA')

# Add title and labels
plt.title('META vs TESLA Stock Price YTD')
plt.xlabel('Date')
plt.ylabel('Closing Price (USD)')

# Add legend
plt.legend()

# Save the plot to a file
plt.savefig('stock_price_ytd.png')

This code will create a line plot of the closing prices of META and TESLA stocks from the start of the year to today, and save the plot to a file named 'stock_price_ytd.png'.


EXECUTING CODE BLOCK 0 (inferred language is python)...
user_proxy (to assistant):

exitcode: 1 (execution failed)
Code output:
Traceback (most recent call last):
File "", line 2, in
import matplotlib.pyplot as plt
ModuleNotFoundError: No module named 'matplotlib'


assistant (to user_proxy):

I apologize for the oversight. It seems that the matplotlib library is not installed in your Python environment. You can install it using pip, which is a package manager for Python. Here is the command to install matplotlib:

# shell script
pip install matplotlib

After installing matplotlib, you can run the previous Python code to plot the stock prices and save the plot to a file.


EXECUTING CODE BLOCK 0 (inferred language is sh)...
SIGALRM is not supported on Windows. No timeout will be enforced.
Exception in thread Thread-12 (_readerthread):
Traceback (most recent call last):
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.1776.0_x64__qbz5n2kfra8p0\Lib\threading.py", line 1045, in _bootstrap_inner
self.run()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.1776.0_x64__qbz5n2kfra8p0\Lib\threading.py", line 982, in run
self._target(*self._args, **self._kwargs)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.1776.0_x64__qbz5n2kfra8p0\Lib\subprocess.py", line 1597, in _readerthread
buffer.append(fh.read())
^^^^^^^^^
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.1776.0_x64__qbz5n2kfra8p0\Lib\encodings\cp1252.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 172: character maps to
Traceback (most recent call last):
File "C:\autogen\venv2\main.py", line 48, in
user_proxy.send(
File "C:\autogen\venv2\venv\Lib\site-packages\autogen\agentchat\conversable_agent.py", line 334, in send
recipient.receive(message, self, request_reply, silent)
File "C:\autogen\venv2\venv\Lib\site-packages\autogen\agentchat\conversable_agent.py", line 464, in receive
self.send(reply, sender, silent=silent)
File "C:\autogen\venv2\venv\Lib\site-packages\autogen\agentchat\conversable_agent.py", line 334, in send
recipient.receive(message, self, request_reply, silent)
File "C:\autogen\venv2\venv\Lib\site-packages\autogen\agentchat\conversable_agent.py", line 464, in receive
self.send(reply, sender, silent=silent)
File "C:\autogen\venv2\venv\Lib\site-packages\autogen\agentchat\conversable_agent.py", line 334, in send
recipient.receive(message, self, request_reply, silent)
File "C:\autogen\venv2\venv\Lib\site-packages\autogen\agentchat\conversable_agent.py", line 464, in receive
self.send(reply, sender, silent=silent)
File "C:\autogen\venv2\venv\Lib\site-packages\autogen\agentchat\conversable_agent.py", line 334, in send
recipient.receive(message, self, request_reply, silent)
File "C:\autogen\venv2\venv\Lib\site-packages\autogen\agentchat\conversable_agent.py", line 462, in receive
reply = self.generate_reply(messages=self.chat_messages[sender], sender=sender)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\autogen\venv2\venv\Lib\site-packages\autogen\agentchat\conversable_agent.py", line 779, in generate_reply
final, reply = reply_func(self, messages=messages, sender=sender, config=reply_func_tuple["config"])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\autogen\venv2\venv\Lib\site-packages\autogen\agentchat\conversable_agent.py", line 635, in generate_code_execution_reply
exitcode, logs = self.execute_code_blocks(code_blocks)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\autogen\venv2\venv\Lib\site-packages\autogen\agentchat\conversable_agent.py", line 900, in execute_code_blocks
exitcode, logs, image = self.run_code(code, lang=lang, **self._code_execution_config)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\autogen\venv2\venv\Lib\site-packages\autogen\agentchat\conversable_agent.py", line 883, in run_code
return execute_code(code, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\autogen\venv2\venv\Lib\site-packages\autogen\code_utils.py", line 323, in execute_code
logs = logs.replace(str(abs_path), "").replace(filename, "")
^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'replace'

Process finished with exit code 1

so every time when the userproxyagent tries to install the "matplotlib" it crashes - when I install it manually and run the script again, it creates the png file as it should

am I doing something wrong here? probably ^_^
thanks

@sonichi
Copy link
Contributor

sonichi commented Oct 14, 2023

It seems that the execution fails while the result.stderr is None. Would you consider using docker?

@schoenia
Copy link
Author

yes - I've tried to get it to work, by changing "use_docker": False to --> "use_docker": True
but I ran into another error at the same stage:

`>>>>>>>> EXECUTING CODE BLOCK 0 (inferred language is python)...
Traceback (most recent call last):
File "C:\autogen\venv2\venv\Lib\site-packages\docker\api\client.py", line 214, in _retrieve_server_version
return self.version(api_version=False)["ApiVersion"]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\autogen\venv2\venv\Lib\site-packages\docker\api\daemon.py", line 181, in version
return self._result(self._get(url), json=True)
^^^^^^^^^^^^^^
File "C:\autogen\venv2\venv\Lib\site-packages\docker\utils\decorators.py", line 46, in inner
return f(self, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\autogen\venv2\venv\Lib\site-packages\docker\api\client.py", line 237, in _get
return self.get(url, **self._set_request_timeout(kwargs))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\autogen\venv2\venv\Lib\site-packages\requests\sessions.py", line 602, in get
return self.request("GET", url, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\autogen\venv2\venv\Lib\site-packages\requests\sessions.py", line 589, in request
resp = self.send(prep, **send_kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\autogen\venv2\venv\Lib\site-packages\requests\sessions.py", line 703, in send
r = adapter.send(request, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\autogen\venv2\venv\Lib\site-packages\requests\adapters.py", line 486, in send
resp = conn.urlopen(
^^^^^^^^^^^^^
File "C:\autogen\venv2\venv\Lib\site-packages\urllib3\connectionpool.py", line 790, in urlopen
response = self._make_request(
^^^^^^^^^^^^^^^^^^^
File "C:\autogen\venv2\venv\Lib\site-packages\urllib3\connectionpool.py", line 496, in _make_request
conn.request(
File "C:\autogen\venv2\venv\Lib\site-packages\urllib3\connection.py", line 395, in request
self.endheaders()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.1776.0_x64__qbz5n2kfra8p0\Lib\http\client.py", line 1281, in endheaders
self._send_output(message_body, encode_chunked=encode_chunked)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.1776.0_x64__qbz5n2kfra8p0\Lib\http\client.py", line 1041, in _send_output
self.send(msg)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.1776.0_x64__qbz5n2kfra8p0\Lib\http\client.py", line 979, in send
self.connect()
File "C:\autogen\venv2\venv\Lib\site-packages\docker\transport\npipeconn.py", line 25, in connect
sock.connect(self.npipe_path)
File "C:\autogen\venv2\venv\Lib\site-packages\docker\transport\npipesocket.py", line 25, in wrapped
return f(self, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\autogen\venv2\venv\Lib\site-packages\docker\transport\npipesocket.py", line 76, in connect
raise e
File "C:\autogen\venv2\venv\Lib\site-packages\docker\transport\npipesocket.py", line 54, in connect
handle = win32file.CreateFile(
^^^^^^^^^^^^^^^^^^^^^
pywintypes.error: (2, 'CreateFile', 'Das System kann die angegebene Datei nicht finden.')

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\autogen\venv2\main.py", line 53, in
user_proxy.initiate_chat(assistant, message="make a snake game")
File "C:\autogen\venv2\venv\Lib\site-packages\autogen\agentchat\conversable_agent.py", line 531, in initiate_chat
self.send(self.generate_init_message(**context), recipient, silent=silent)
File "C:\autogen\venv2\venv\Lib\site-packages\autogen\agentchat\conversable_agent.py", line 334, in send
recipient.receive(message, self, request_reply, silent)
File "C:\autogen\venv2\venv\Lib\site-packages\autogen\agentchat\conversable_agent.py", line 464, in receive
self.send(reply, sender, silent=silent)
File "C:\autogen\venv2\venv\Lib\site-packages\autogen\agentchat\conversable_agent.py", line 334, in send
recipient.receive(message, self, request_reply, silent)
File "C:\autogen\venv2\venv\Lib\site-packages\autogen\agentchat\conversable_agent.py", line 462, in receive
reply = self.generate_reply(messages=self.chat_messages[sender], sender=sender)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\autogen\venv2\venv\Lib\site-packages\autogen\agentchat\conversable_agent.py", line 779, in generate_reply
final, reply = reply_func(self, messages=messages, sender=sender, config=reply_func_tuple["config"])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\autogen\venv2\venv\Lib\site-packages\autogen\agentchat\conversable_agent.py", line 635, in generate_code_execution_reply
exitcode, logs = self.execute_code_blocks(code_blocks)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\autogen\venv2\venv\Lib\site-packages\autogen\agentchat\conversable_agent.py", line 906, in execute_code_blocks
exitcode, logs, image = self.run_code(
^^^^^^^^^^^^^^
File "C:\autogen\venv2\venv\Lib\site-packages\autogen\agentchat\conversable_agent.py", line 883, in run_code
return execute_code(code, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\autogen\venv2\venv\Lib\site-packages\autogen\code_utils.py", line 332, in execute_code
client = docker.from_env()
^^^^^^^^^^^^^^^^^
File "C:\autogen\venv2\venv\Lib\site-packages\docker\client.py", line 96, in from_env
return cls(
^^^^
File "C:\autogen\venv2\venv\Lib\site-packages\docker\client.py", line 45, in init
self.api = APIClient(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\autogen\venv2\venv\Lib\site-packages\docker\api\client.py", line 197, in init
self._version = self._retrieve_server_version()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\autogen\venv2\venv\Lib\site-packages\docker\api\client.py", line 221, in _retrieve_server_version
raise DockerException(
docker.errors.DockerException: Error while fetching server API version: (2, 'CreateFile', 'Das System kann die angegebene Datei nicht finden.')

Process finished with exit code 1
`

is there some extra configuration needed to use docker?

@schoenia
Copy link
Author

got it sorted:

installing docker for windows (using wsl)
updating wsl --> wsl --update
installing plugin in pycharm

works!

@binary-husky
Copy link
Collaborator

Funny that a project by microsoft does not support windows by default

@HAL9KKK
Copy link

HAL9KKK commented Oct 26, 2023

got it sorted:

installing docker for windows (using wsl) updating wsl --> wsl --update installing plugin in pycharm

works!

Could you please describe in detail the steps to do in windows?

@bigc90210
Copy link

id also appreciate the steps :)

@anuragsirish
Copy link

same here

@miraculix95
Copy link

Why is this still not corrected? Autogen? 50% of people use Windows, they try the example, and nothing works

jackgerrits pushed a commit that referenced this issue Oct 2, 2024
* Add token counting to chat completion client

* fix mypy

* ignore pyright for object type

* format
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

No branches or pull requests

7 participants