Skip to content

Commit 7f7001c

Browse files
committed
Initial commit
0 parents  commit 7f7001c

17 files changed

+1148
-0
lines changed

code_exec_cmdline.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# Testing the Code Executor - Local Command Line - NO LLM
2+
# Based on: https://github.com/microsoft/autogen/blob/tutorial/website/docs/getting-started/code-executors.ipynb
3+
4+
import os
5+
import tempfile
6+
import shutil
7+
from autogen import ConversableAgent, UserProxyAgent, AssistantAgent
8+
9+
# Here is an example of using the local command line code executor to run a Python code block that
10+
# prints a random number. First we create an agent with the local command line code executor that
11+
# uses a temporary directory to store the code files.
12+
13+
# Create a temporary directory to store the code files.
14+
temp_dir = tempfile.mkdtemp()
15+
16+
# Create an agent with code executor configuration for a local command line
17+
# code executor.
18+
code_executor_agent = ConversableAgent(
19+
"code_executor_agent",
20+
llm_config=False, # Turn off LLM for this agent.
21+
code_execution_config={
22+
"executor": "commandline-local", # Use the local command line executor.
23+
"commandline-local": {
24+
"timeout": 10, # Timeout for each code execution in seconds.
25+
"work_dir": temp_dir, # Use the temporary directory to store the code files.
26+
},
27+
},
28+
human_input_mode="ALWAYS", # Always take human input for this agent for safety.
29+
)
30+
31+
# Now we have the agent generate a reply given a message with a Python code block.
32+
33+
message_with_code_block = (
34+
"This is a message with code block. "
35+
"The code block is below: \n"
36+
"```python\n"
37+
"import random\n"
38+
"print('A Random Number: ', random.randint(1, 100))\n"
39+
"```\n"
40+
"This is the end of the message.\n"
41+
)
42+
43+
# Generate a reply for the given code.
44+
reply = code_executor_agent.generate_reply(messages=[{"role": "user", "content": message_with_code_block}])
45+
print(reply)
46+
47+
# Look at the temporary file created
48+
print("Temporary file created and contents:")
49+
code_files = os.listdir(temp_dir)
50+
print(code_files)
51+
print(open(os.path.join(temp_dir, code_files[0])).read())
52+
53+
# Clean up the temporary directory
54+
shutil.rmtree(temp_dir)

code_exec_jupyter.py

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
# Testing the Code Executor - Local Jupyter - NO LLM
2+
# Based on: https://github.com/microsoft/autogen/blob/tutorial/website/docs/getting-started/code-executors.ipynb
3+
4+
# Installed: pip install -qqq 'pyautogen[local-jupyter-exec]'
5+
6+
import os
7+
import tempfile
8+
import shutil
9+
from autogen import ConversableAgent, UserProxyAgent, AssistantAgent
10+
from IPython.display import Image
11+
12+
# We create an agent with a local Jupyter code executor, and asks it to generates a reply
13+
# with a given code block in markdown.
14+
15+
# Create a temporary directory to store the code files.
16+
temp_dir = tempfile.mkdtemp()
17+
18+
# Create an agent with code executor configuration for a local Jupyter
19+
# code executor.
20+
jupyter_agent = ConversableAgent(
21+
name="Jupyter_Agent",
22+
llm_config=False,
23+
code_execution_config={
24+
"executor": "jupyter-local", # Use the local Jupyter executor.
25+
# On Windows use "ipython-embedded" instead of "jupyter-local"
26+
# due to a known issue with Jupyter Kernel Gateway on Windows.
27+
"jupyter-local": {
28+
"timeout": 60, # Timeout for each code execution in seconds.
29+
"kernel_name": "python3", # Use the Python 3 kernel, which is the default.
30+
"output_dir": temp_dir, # Use the temporary directory to store output images.
31+
},
32+
},
33+
human_input_mode="ALWAYS",
34+
)
35+
36+
# Ask the agent to generate a reply for a message that contains two Python code blocks.
37+
38+
message_with_code_blocks_1 = (
39+
"First import the required libraries: \n"
40+
"```python\n"
41+
"import numpy as np\n"
42+
"import matplotlib.pyplot as plt\n"
43+
"```\n"
44+
"\n"
45+
"Now let's generate random numbers.\n"
46+
"```python\n"
47+
"np.random.seed(0)\n"
48+
"x = np.random.rand(100)\n"
49+
"y = np.random.rand(100)\n"
50+
"````n"
51+
)
52+
53+
# Generate a reply for the first code message.
54+
reply = jupyter_agent.generate_reply(
55+
messages=[
56+
{
57+
"role": "user",
58+
"content": message_with_code_blocks_1,
59+
}
60+
]
61+
)
62+
print(reply)
63+
64+
# Ask the agent to generate a reply for a message that contains a Python code block that
65+
# generates a plot using the variables from the code block in the previous message.
66+
67+
message_with_code_blocks_2 = (
68+
"Now let's plot the random numbers. \n"
69+
"```python\n"
70+
"plt.scatter(x, y)\n"
71+
"plt.xlabel('X')\n"
72+
"plt.ylabel('Y')\n"
73+
"plt.title('Random Numbers')\n"
74+
"plt.show()\n"
75+
"```\n"
76+
)
77+
78+
# Generate a reply for the second code message.
79+
reply = jupyter_agent.generate_reply(
80+
messages=[
81+
{
82+
"role": "user",
83+
"content": message_with_code_blocks_2,
84+
}
85+
]
86+
)
87+
print(reply)
88+
89+
# Look at the generated image
90+
output_files = os.listdir(temp_dir)
91+
print(output_files)
92+
Image(os.path.join(temp_dir, output_files[0]))
93+
94+
# Clean up the temporary directory
95+
# shutil.rmtree(temp_dir)

code_exec_jupyter_llm.py

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
# Testing the Code Executor - Local Jupyter - Local LLM
2+
# Based on: https://github.com/microsoft/autogen/blob/tutorial/website/docs/getting-started/code-executors.ipynb
3+
4+
# Installed: pip install -qqq 'pyautogen[local-jupyter-exec]'
5+
6+
import os
7+
import tempfile
8+
import shutil
9+
from autogen import ConversableAgent, UserProxyAgent, AssistantAgent
10+
from IPython.display import Image
11+
12+
# The code writer agent can be powered by an LLM such as GPT-4 with code-writing capability.
13+
# And the code executor agent is powered by a code executor.
14+
15+
# The following is an agent with a code writer role specified using system_message.
16+
17+
# The code writer agent's system message is to instruct the LLM on how to
18+
# use the Jupyter code executor with IPython kernel.
19+
code_writer_system_message = (
20+
"You have been given coding capability to solve tasks using Python code in a stateful IPython kernel.\n"
21+
"You are responsible for writing the code, and the user is responsible for executing the code.\n"
22+
"\n"
23+
"When you write Python code, put the code in a markdown code block with the language set to Python.\n"
24+
"For example:\n"
25+
"```python\n"
26+
"x = 3\n"
27+
"```\n"
28+
"You can use the variable `x` in subsequent code blocks.\n"
29+
"```python\n"
30+
"print(x)\n"
31+
"```\n"
32+
"\n"
33+
"Write code incrementally and leverage the statefulness of the kernel to avoid repeating code.\n"
34+
"Import libraries in a separate code block.\n"
35+
"Define a function or a class in a separate code block.\n"
36+
"Run code that produces output in a separate code block.\n"
37+
"Run code that involves expensive operations like download, upload, and call external APIs in a separate code block.\n"
38+
"\n"
39+
"When your code produces an output, the output will be returned to you.\n"
40+
"Because you have limited conversation memory, if your code creates an image,\n"
41+
"the output will be a path to the image instead of the image itself.\n"
42+
)
43+
44+
# MS - LLM will be the one running on my machine using liteLLM, port 8801, name doesn't mean anything in this case.
45+
# Command to run LiteLLM: litellm --model ollama/phind-codellama:34b-v2 --port 8801
46+
code_writer_agent = ConversableAgent(
47+
"code_writer",
48+
system_message=code_writer_system_message,
49+
llm_config={
50+
"config_list": [{"model": "Local8801", "api_key": "NotRequired", "base_url": "http://192.168.0.115:8801"}],
51+
"cache_seed": None,
52+
}, ## CRITICAL - ENSURE THERE'S NO CACHING FOR TESTING
53+
code_execution_config=False, # Turn off code execution for this agent.
54+
)
55+
56+
# Create a temporary directory to store the output images.
57+
temp_dir = tempfile.mkdtemp()
58+
59+
# Create an agent with code executor configuration for a local Jupyter
60+
# code executor.
61+
code_executor_agent = ConversableAgent(
62+
name="code_executor_agent",
63+
llm_config=False,
64+
code_execution_config={
65+
"executor": "jupyter-local", # Use the local Jupyter executor.
66+
# On Windows use "ipython-embedded" instead of "jupyter-local"
67+
# due to a known issue with Jupyter Kernel Gateway on Windows.
68+
"jupyter-local": {
69+
"timeout": 60, # Timeout for each code execution in seconds.
70+
"kernel_name": "python3", # Use the Python 3 kernel, which is the default.
71+
"output_dir": temp_dir, # Use the temporary directory to store output images.
72+
},
73+
},
74+
human_input_mode="ALWAYS",
75+
)
76+
77+
# Here is an example of solving a math problem through a conversation between the code writer and the code executor:
78+
79+
chat_result = code_executor_agent.initiate_chat(
80+
code_writer_agent,
81+
message="Write Python code to calculate the 14th Fibonacci number.",
82+
)
83+
84+
# Clean up the temporary directory and restart the Jupyter server to free up the kernel resources.
85+
86+
shutil.rmtree(temp_dir)
87+
code_executor_agent.code_executor.restart()
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
ode_executor_agent (to code_writer):
2+
3+
Write Python code to calculate the 14th Fibonacci number.
4+
5+
--------------------------------------------------------------------------------
6+
7+
>>>>>>>> USING AUTO REPLY...
8+
code_writer (to code_executor_agent):
9+
10+
Sure, I can help with that. The Fibonacci sequence is defined by starting with two ones and then each subsequent number is the sum of the previous two numbers in the series. Here's how you could calculate the 14th Fibonacci number using Python:
11+
12+
```python
13+
def fib(n):
14+
a, b = 0, 1
15+
for _ in range(n):
16+
a, b = b, a + b
17+
return a
18+
19+
print(fib(14))
20+
```
21+
This function `fib` generates the nth Fibonacci number by starting with two initial values (0 and 1) and then updating these to be the last two numbers in the sequence. This is done using a for loop that runs n times, each time shifting the values of a and b one step further down the sequence.
22+
23+
When you run this code, it will print out the 14th Fibonacci number which should be `377`.
24+
25+
26+
--------------------------------------------------------------------------------
27+
Provide feedback to code_writer. Press enter to skip and use auto-reply, or type 'exit' to end the conversation:
28+
29+
>>>>>>>> NO HUMAN INPUT RECEIVED.
30+
31+
>>>>>>>> USING AUTO REPLY...
32+
code_executor_agent (to code_writer):
33+
34+
exitcode: 0 (execution succeeded)
35+
Code output: 377
36+
37+
38+
--------------------------------------------------------------------------------
39+
40+
>>>>>>>> USING AUTO REPLY...
41+
code_writer (to code_executor_agent):
42+
43+
Great! I'm glad to hear that the code ran successfully and produced the expected output of 377, which is the 14th number in the Fibonacci sequence. If you have any other questions or need further clarification on Python programming, feel free to ask!
44+
45+
46+
--------------------------------------------------------------------------------
47+
Provide feedback to code_writer. Press enter to skip and use auto-reply, or type 'exit' to end the conversation: exit
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
code_executor_agent (to code_writer):
2+
3+
Write Python code to calculate the 14th Fibonacci number.
4+
5+
--------------------------------------------------------------------------------
6+
7+
>>>>>>>> USING AUTO REPLY...
8+
code_writer (to code_executor_agent):
9+
10+
```python
11+
# Import the necessary library
12+
import math
13+
14+
# Define a function to calculate the nth Fibonacci number
15+
def fibonacci(n):
16+
if n <= 1:
17+
return n
18+
else:
19+
return fibonacci(n-1) + fibonacci(n-2)
20+
21+
# Calculate the 14th Fibonacci number
22+
x = fibonacci(14)
23+
24+
# Print the result
25+
print(x)
26+
```
27+
28+
--------------------------------------------------------------------------------
29+
Provide feedback to code_writer. Press enter to skip and use auto-reply, or type 'exit' to end the conversation:
30+
31+
>>>>>>>> NO HUMAN INPUT RECEIVED.
32+
33+
>>>>>>>> USING AUTO REPLY...
34+
code_executor_agent (to code_writer):
35+
36+
exitcode: 0 (execution succeeded)
37+
Code output: 377
38+
39+
40+
--------------------------------------------------------------------------------
41+
42+
>>>>>>>> USING AUTO REPLY...
43+
code_writer (to code_executor_agent):
44+
45+
Sure! I'm ready to help you with your Python coding needs. Here's the code for the 14th Fibonacci number:
46+
```python
47+
# Import the necessary library
48+
import math
49+
50+
# Define a function to calculate the nth Fibonacci number
51+
def fibonacci(n):
52+
if n <= 1:
53+
return n
54+
else:
55+
return fibonacci(n-1) + fibonacci(n-2)
56+
57+
# Calculate the 14th Fibonacci number
58+
x = fibonacci(14)
59+
60+
# Print the result
61+
print(x)
62+
```
63+
This code imports the `math` library and defines a function `fibonacci` that calculates the nth Fibonacci number. The function uses recursion to calculate the previous two Fibonacci numbers and then adds them together to get the next one. The function returns the result of the calculation.
64+
65+
The code then calls the `fibonacci` function with the argument `14` and stores the result in the variable `x`. Finally, the code prints the result using the `print` function.
66+
67+
When you run this code, it will output the value of the 14th Fibonacci number, which is 377.
68+
69+
--------------------------------------------------------------------------------
70+
Provide feedback to code_writer. Press enter to skip and use auto-reply, or type 'exit' to end the conversation: exit

0 commit comments

Comments
 (0)