AI Agents Examples
Learn how to integrate AI Computer with AI agents and language models to create intelligent systems that can write and execute code safely.
Basic AI Agent Integration
Create a simple AI agent that can generate and execute code:
1import asyncio
2import openai
3from ai_computer import SandboxClient
4
5async def ai_code_executor(prompt: str):
6 # Initialize OpenAI client
7 openai_client = openai.AsyncOpenAI()
8
9 # Initialize sandbox
10 sandbox = SandboxClient()
11 await sandbox.setup()
12
13 try:
14 # Generate code using OpenAI
15 response = await openai_client.chat.completions.create(
16 model="gpt-3.5-turbo",
17 messages=[
18 {"role": "system", "content": "You are a Python code generator."},
19 {"role": "user", "content": f"Write Python code to: {prompt}"}
20 ]
21 )
22
23 # Extract the generated code
24 generated_code = response.choices[0].message.content
25 print("Generated code:")
26 print(generated_code)
27
28 # Execute the generated code
29 print("\nExecuting code...")
30 execution_response = await sandbox.execute_code(generated_code)
31
32 if execution_response.success:
33 print("Execution result:")
34 print(execution_response.data['output'])
35 else:
36 print("Execution failed:", execution_response.error)
37
38 finally:
39 await sandbox.cleanup()
40
41# Example usage
42async def main():
43 prompt = "Calculate the first 10 Fibonacci numbers"
44 await ai_code_executor(prompt)
45
46asyncio.run(main())
Interactive AI Agent
Create an AI agent that can interact with its execution environment:
1import asyncio
2import openai
3from ai_computer import SandboxClient
4
5async def interactive_ai_agent(task: str):
6 openai_client = openai.AsyncOpenAI()
7 sandbox = SandboxClient()
8 await sandbox.setup()
9
10 try:
11 conversation = [
12 {"role": "system", "content": """You are a Python coding assistant.
13You can write and execute code, and learn from the results."""},
14 {"role": "user", "content": f"Task: {task}"}
15 ]
16
17 # Main interaction loop
18 for _ in range(3): # Maximum 3 attempts
19 # Get AI response
20 response = await openai_client.chat.completions.create(
21 model="gpt-3.5-turbo",
22 messages=conversation
23 )
24
25 # Extract code from AI response
26 ai_message = response.choices[0].message.content
27 print("\nAI: ", ai_message)
28
29 # Execute the code
30 print("\nExecuting code...")
31 execution_response = await sandbox.execute_code_stream(ai_message)
32
33 # Collect execution results
34 output = []
35 error_occurred = False
36
37 async for event in execution_response:
38 if event.type == 'stdout':
39 print("Output:", event.data)
40 output.append(event.data)
41 elif event.type == 'stderr':
42 print("Error:", event.data)
43 error_occurred = True
44 output.append(f"Error: {event.data}")
45 elif event.type == 'error':
46 print("Execution error:", event.data)
47 error_occurred = True
48 output.append(f"Execution error: {event.data}")
49
50 # Add execution result to conversation
51 execution_result = "\n".join(output)
52 conversation.append({"role": "assistant", "content": ai_message})
53 conversation.append({"role": "user",
54 "content": f"Execution result:\n{execution_result}"})
55
56 if not error_occurred:
57 break
58
59 conversation.append({"role": "user",
60 "content": "There was an error. Please fix the code and try again."})
61
62 finally:
63 await sandbox.cleanup()
64
65# Example usage
66async def main():
67 task = "Create a function that sorts a list of numbers and removes duplicates"
68 await interactive_ai_agent(task)
69
70asyncio.run(main())
AI Code Review
Use AI to review and test code:
1import asyncio
2import openai
3from ai_computer import SandboxClient
4
5async def ai_code_review(code: str):
6 openai_client = openai.AsyncOpenAI()
7 sandbox = SandboxClient()
8 await sandbox.setup()
9
10 try:
11 # Generate test cases using AI
12 test_response = await openai_client.chat.completions.create(
13 model="gpt-3.5-turbo",
14 messages=[
15 {"role": "system", "content": "You are a Python testing expert."},
16 {"role": "user", "content": f"Write test cases for this code:\n{code}"}
17 ]
18 )
19
20 test_code = test_response.choices[0].message.content
21 print("Generated test cases:")
22 print(test_code)
23
24 # Combine code and tests
25 full_code = f"{code}\n\n{test_code}"
26
27 # Execute tests
28 print("\nRunning tests...")
29 async for event in sandbox.execute_code_stream(full_code):
30 if event.type == 'stdout':
31 print("Output:", event.data)
32 elif event.type == 'stderr':
33 print("Error:", event.data)
34 elif event.type == 'error':
35 print("Execution error:", event.data)
36
37 # Get AI analysis of results
38 analysis_response = await openai_client.chat.completions.create(
39 model="gpt-3.5-turbo",
40 messages=[
41 {"role": "system", "content": "You are a code review expert."},
42 {"role": "user", "content": f"Review this code and suggest improvements:\n{code}"}
43 ]
44 )
45
46 print("\nCode Review:")
47 print(analysis_response.choices[0].message.content)
48
49 finally:
50 await sandbox.cleanup()
51
52# Example usage
53async def main():
54 code = """
55def bubble_sort(arr):
56 n = len(arr)
57 for i in range(n):
58 for j in range(0, n-i-1):
59 if arr[j] > arr[j+1]:
60 arr[j], arr[j+1] = arr[j+1], arr[j]
61 return arr
62"""
63 await ai_code_review(code)
64
65asyncio.run(main())
AI-Assisted Debugging
Use AI to help debug code issues:
1import asyncio
2import openai
3from ai_computer import SandboxClient
4
5async def ai_debug_assistant(code: str, error_message: str):
6 openai_client = openai.AsyncOpenAI()
7 sandbox = SandboxClient()
8 await sandbox.setup()
9
10 try:
11 # Get AI analysis of the error
12 debug_response = await openai_client.chat.completions.create(
13 model="gpt-3.5-turbo",
14 messages=[
15 {"role": "system", "content": "You are a Python debugging expert."},
16 {"role": "user", "content": f"""
17Help debug this code:
18
19Code:
20{code}
21
22Error:
23{error_message}
24
25Suggest a fix and explain the issue."""}
26 ]
27 )
28
29 analysis = debug_response.choices[0].message.content
30 print("AI Analysis:")
31 print(analysis)
32
33 # Extract fixed code from AI response
34 fix_response = await openai_client.chat.completions.create(
35 model="gpt-3.5-turbo",
36 messages=[
37 {"role": "system", "content": "Provide only the fixed code without explanation."},
38 {"role": "user", "content": f"Fix this code:\n{code}"}
39 ]
40 )
41
42 fixed_code = fix_response.choices[0].message.content
43 print("\nTesting fixed code...")
44
45 # Test the fixed code
46 async for event in sandbox.execute_code_stream(fixed_code):
47 if event.type == 'stdout':
48 print("Output:", event.data)
49 elif event.type == 'stderr':
50 print("Error:", event.data)
51 elif event.type == 'error':
52 print("Execution error:", event.data)
53
54 finally:
55 await sandbox.cleanup()
56
57# Example usage
58async def main():
59 code = """
60def calculate_average(numbers):
61 total = 0
62 for num in numbers
63 total += num
64 return total / len(numbers)
65
66test_numbers = [1, 2, 3, 4, 5]
67result = calculate_average(test_numbers)
68print(f"Average: {result}")
69"""
70 error_message = "SyntaxError: invalid syntax"
71 await ai_debug_assistant(code, error_message)
72
73asyncio.run(main())
Best Practices
1. Validate AI-Generated Code
Always validate and test AI-generated code before using it in production.
2. Handle AI API Errors
Implement proper error handling for both AI API calls and code execution.
3. Use Clear Prompts
Provide clear and specific prompts to get better code from AI models.
4. Implement Retry Logic
Add retry mechanisms for both AI API calls and code execution attempts.