Skip to content

Commit

Permalink
Update main.py
Browse files Browse the repository at this point in the history
  • Loading branch information
Doriandarko authored Jul 5, 2024
1 parent 8841e8e commit 5050de4
Showing 1 changed file with 82 additions and 86 deletions.
168 changes: 82 additions & 86 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,9 @@
TOOL_COLOR = Fore.YELLOW
RESULT_COLOR = Fore.GREEN

# Constants
# Add these constants at the top of the file
CONTINUATION_EXIT_PHRASE = "AUTOMODE_COMPLETE"
MAX_CONTINUATION_ITERATIONS = 25
MODEL = os.environ.get("CLAUDE_MODEL", "claude-3-5-sonnet-20240620")
TOOL_CHOICE = {"type": os.environ.get("TOOL_CHOICE", "auto")}

# Initialize the Anthropic client
client = Anthropic(api_key="YOUR KEY")
Expand All @@ -41,67 +39,57 @@
# automode flag
automode = False

# System prompt
# System prompt
system_prompt = """
You are Claude, an AI assistant powered by Anthropic's Claude-3.5-Sonnet model. You are a versatile software developer and problem-solver with access to various tools and capabilities. Your primary function is to assist users with coding tasks, answer questions, and provide up-to-date information.
Your available tools and their functions are:
1. create_folder(path): Create a new folder at the specified path.
2. create_file(path, content=""): Create a new file at the specified path with optional content.
3. write_to_file(path, content): Write or update content in a file at the specified path.
4. read_file(path): Read and return the contents of a file at the specified path.
5. list_files(path="."): List all files and directories in the specified folder (default is current directory).
6. tavily_search(query): Perform a web search using the Tavily API to get up-to-date information.
When using these tools:
- Always provide full paths for file and folder operations.
- Use the read_file tool before attempting to modify existing files.
- Utilize the tavily_search tool when you need current information or additional context.
- Use the list_files tool to understand the project structure when necessary.
Your capabilities include:
1. Creating and managing project structures, including folders and files.
2. Writing, reading, and modifying code in various programming languages.
3. Debugging issues and providing detailed explanations.
4. Offering architectural insights and suggesting design patterns.
5. Staying informed about the latest technologies and industry trends.
6. Analyzing and describing images provided by the user.
When working on projects or answering questions:
- Start by creating a root folder for new projects, then add necessary subdirectories and files.
- Organize project structures logically, following best practices for the specific type of project.
- Provide clean, efficient, and well-documented code.
- Use the tavily_search tool to gather up-to-date information when needed.
- When editing files, always provide the full content, even for small changes.
Before using any tool, analyze the request within <thinking></thinking> tags:
1. Determine which tool is most appropriate for the task.
2. Consider if all required parameters are provided or can be reasonably inferred.
3. If a required parameter is missing, ask the user for the necessary information instead of using the tool.
4. Do not ask for optional parameters if they are not provided.
Special modes:
- Automode: When activated, work autonomously to complete tasks, providing regular updates on your progress.
- Image analysis: When an image is provided, carefully analyze its contents and incorporate your observations into your responses.
Automode Operation:
When in automode, follow these steps:
1. Set clear, achievable goals based on the user's request.
2. Work through these goals one by one, using the available tools as needed.
3. Provide regular updates on your progress.
4. ULTRA MEGA IMPORTANT: When you believe all goals have been completed or the original request has been fully addressed, include the phrase "AUTOMODE_COMPLETE" in your response. This will signal the system to exit the automode loop.
5. Do not engage in unnecessary back-and-forth conversations with yourself once the goals are achieved.
6. Be mindful of the number of iterations left (provided in {iteration_info}) and use this information to pace your work and provide appropriate updates.
Always strive to provide accurate, helpful, and detailed responses. If you're unsure about something, admit it and consider using the tavily_search tool to find the most current information.
Remember, you are here to assist and guide the user. Be proactive in suggesting solutions and offering advice, but also be receptive to the user's preferences and instructions.
You are Claude, an AI assistant powered by Anthropic's Claude-3.5-Sonnet model. You are an exceptional software developer with vast knowledge across multiple programming languages, frameworks, and best practices. Your capabilities include:
1. Creating project structures, including folders and files
2. Writing clean, efficient, and well-documented code
3. Debugging complex issues and providing detailed explanations
4. Offering architectural insights and design patterns
5. Staying up-to-date with the latest technologies and industry trends
6. Reading and analyzing existing files in the project directory
7. Listing files in the root directory of the project
8. Performing web searches to get up-to-date information or additional context
9. When you use search make sure you use the best query to get the most accurate and up-to-date information
10. IMPORTANT!! When editing files, always provide the full content of the file, even if you're only changing a small part. The system will automatically generate and apply the appropriate diff.
11. Analyzing images provided by the user
When an image is provided, carefully analyze its contents and incorporate your observations into your responses.
When asked to create a project:
- Always start by creating a root folder for the project.
- Then, create the necessary subdirectories and files within that root folder.
- Organize the project structure logically and follow best practices for the specific type of project being created.
- Use the provided tools to create folders and files as needed.
When asked to make edits or improvements:
- Use the read_file tool to examine the contents of existing files.
- Analyze the code and suggest improvements or make necessary edits.
- Use the write_to_file tool to implement changes, providing the full updated file content.
Be sure to consider the type of project (e.g., Python, JavaScript, web application) when determining the appropriate structure and files to include.
You can now read files, list the contents of the root folder where this script is being run, and perform web searches. Use these capabilities when:
- The user asks for edits or improvements to existing files
- You need to understand the current state of the project
- You believe reading a file or listing directory contents will be beneficial to accomplish the user's goal
- You need up-to-date information or additional context to answer a question accurately
When you need current information or feel that a search could provide a better answer, use the tavily_search tool. This tool performs a web search and returns a concise answer along with relevant sources.
Always strive to provide the most accurate, helpful, and detailed responses possible. If you're unsure about something, admit it and consider using the search tool to find the most current information.
{automode_status}
{iteration_info}
When in automode:
1. Set clear, achievable goals for yourself based on the user's request
2. Work through these goals one by one, using the available tools as needed
3. REMEMBER!! You can Read files, write code, LIST the files, and even SEARCH and make edits, use these tools as necessary to accomplish each goal
4. ALWAYS READ A FILE BEFORE EDITING IT IF YOU ARE MISSING CONTENT. Provide regular updates on your progress
5. IMPORTANT RULe!! When you know your goals are completed, DO NOT CONTINUE IN POINTLESS BACK AND FORTH CONVERSATIONS with yourself, if you think we achieved the results established to the original request say "AUTOMODE_COMPLETE" in your response to exit the loop!
6. ULTRA IMPORTANT! You have access to this {iteration_info} amount of iterations you have left to complete the request, you can use this information to make decisions and to provide updates on your progress knowing the amount of responses you have left to complete the request.
Answer the user's request using relevant tools (if they are available). Before calling a tool, do some analysis within <thinking></thinking> tags. First, think about which of the provided tools is the relevant tool to answer the user's request. Second, go through each of the required parameters of the relevant tool and determine if the user has directly provided or given enough information to infer a value. When deciding if the parameter can be inferred, carefully consider all the context to see if it supports a specific value. If all of the required parameters are present or can be reasonably inferred, close the thinking tag and proceed with the tool call. BUT, if one of the values for a required parameter is missing, DO NOT invoke the function (not even with fillers for the missing params) and instead, ask the user to provide the missing parameters. DO NOT ask for more information on optional parameters if it is not provided.
"""

def update_system_prompt(current_iteration=None, max_iterations=None):
Expand Down Expand Up @@ -330,7 +318,7 @@ def execute_goals(goals):
print_colored("Exiting automode.", TOOL_COLOR)
break

def chat_with_claude(user_input, image_path=None, current_iteration=None, max_iterations=None, max_tokens=4000):
def chat_with_claude(user_input, image_path=None, current_iteration=None, max_iterations=None):
global conversation_history, automode

if image_path:
Expand Down Expand Up @@ -365,28 +353,26 @@ def chat_with_claude(user_input, image_path=None, current_iteration=None, max_it

messages = [msg for msg in conversation_history if msg.get('content')]



try:
response = client.messages.create(
model=MODEL,
max_tokens=max_tokens,
model="claude-3-5-sonnet-20240620",
max_tokens=4000,
system=update_system_prompt(current_iteration, max_iterations),
messages=messages,
tools=tools,
tool_choice=TOOL_CHOICE
tool_choice={"type": "auto"}
)
except Exception as e:
print_colored(f"Error calling Claude API: {str(e)}", TOOL_COLOR)
return "I'm sorry, there was an error communicating with the AI. Please try again.", False

assistant_response = ""
exit_continuation = False
tool_use_blocks = []

for content_block in response.content:
if content_block.type == "text":
assistant_response += content_block.text
print_colored(f"\nClaude: {content_block.text}", CLAUDE_COLOR)
if CONTINUATION_EXIT_PHRASE in content_block.text:
exit_continuation = True
elif content_block.type == "tool_use":
Expand All @@ -398,31 +384,41 @@ def chat_with_claude(user_input, image_path=None, current_iteration=None, max_it
print_colored(f"Tool Input: {tool_input}", TOOL_COLOR)

result = execute_tool(tool_name, tool_input)
if isinstance(result, dict) and result.get("is_error"):
print_colored(f"Tool Error: {result['content']}", TOOL_COLOR)
else:
print_colored(f"Tool Result: {result}", RESULT_COLOR)
print_colored(f"Tool Result: {result}", RESULT_COLOR)

tool_use_blocks.append(content_block)
tool_result = {
"type": "tool_result",
"tool_use_id": tool_use_id,
"content": result if isinstance(result, str) else result["content"],
"is_error": result.get("is_error", False) if isinstance(result, dict) else False
}

# Immediately add tool use and tool result to conversation history
conversation_history.append({"role": "assistant", "content": [content_block]})
conversation_history.append({"role": "user", "content": [tool_result]})
conversation_history.append({
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": tool_use_id,
"content": result
}
]
})

try:
tool_response = client.messages.create(
model="claude-3-5-sonnet-20240620",
max_tokens=4000,
system=update_system_prompt(current_iteration, max_iterations),
messages=[msg for msg in conversation_history if msg.get('content')],
tools=tools,
tool_choice={"type": "auto"}
)

for tool_content_block in tool_response.content:
if tool_content_block.type == "text":
assistant_response += tool_content_block.text
print_colored(f"\nClaude: {tool_content_block.text}", CLAUDE_COLOR)
except Exception as e:
print_colored(f"Error in tool response: {str(e)}", TOOL_COLOR)
assistant_response += "\nI encountered an error while processing the tool result. Please try again."

# Add the final assistant response to the conversation history
if assistant_response:
conversation_history.append({"role": "assistant", "content": assistant_response})

actual_input_tokens = response.usage.input_tokens
actual_output_tokens = response.usage.output_tokens
print_colored(f"Actual token usage - Input: {actual_input_tokens}, Output: {actual_output_tokens}", TOOL_COLOR)

return assistant_response, exit_continuation

def process_and_display_response(response):
Expand Down

0 comments on commit 5050de4

Please sign in to comment.