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

update .openhands instructions #5821

Merged
merged 13 commits into from
Dec 26, 2024
File renamed without changes.
2 changes: 1 addition & 1 deletion docs/modules/usage/getting-started.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -108,4 +108,4 @@ to get the most out of it. Remember to:
* Provide as much context as possible
* Commit and push frequently

See [Prompting Best Practices](./prompting-best-practices) for more tips on how to get the most out of OpenHands.
See [Prompting Best Practices](./prompting/prompting-best-practices) for more tips on how to get the most out of OpenHands.
59 changes: 0 additions & 59 deletions docs/modules/usage/how-to/github-action.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,62 +48,3 @@ The customization options you can set are:
| `OPENHANDS_MAX_ITER` | Variable | Set max limit for agent iterations | `OPENHANDS_MAX_ITER=10` |
| `OPENHANDS_MACRO` | Variable | Customize default macro for invoking the resolver | `OPENHANDS_MACRO=@resolveit` |
| `OPENHANDS_BASE_CONTAINER_IMAGE` | Variable | Custom Sandbox ([learn more](https://docs.all-hands.dev/modules/usage/how-to/custom-sandbox-guide)) | `OPENHANDS_BASE_CONTAINER_IMAGE="custom_image"` |

## Writing Effective .openhands_instructions Files

The `.openhands_instructions` file is a file that you can put in the root directory of your repository to guide OpenHands
in understanding and working with your repository effectively. Here are key tips for writing high-quality instructions:

### Core Principles

1. **Concise but Informative**: Provide a clear, focused overview of the repository that emphasizes the most common
actions OpenHands will need to perform.

2. **Repository Structure**: Explain the key directories and their purposes, especially highlighting where different
types of code (e.g., frontend, backend) are located.

3. **Development Workflows**: Document the essential commands for:

- Building and setting up the project
- Running tests
- Linting and code quality checks
- Any environment-specific requirements

4. **Testing Guidelines**: Specify:
- Where tests are located
- How to run specific test suites
- Any testing conventions or requirements

### Example Structure

```markdown
# Repository Overview

[Brief description of the project]

## General Setup

- Main build command
- Development environment setup
- Pre-commit checks

## Backend

- Location and structure
- Testing instructions
- Environment requirements

## Frontend

- Setup prerequisites
- Build and test commands
- Environment variables

## Additional Guidelines

- Code style requirements
- Special considerations
- Common workflows
```

For a real-world example, refer to the [OpenHands repository's .openhands_instructions](https://github.com/All-Hands-AI/OpenHands/blob/main/.openhands_instructions).
2 changes: 1 addition & 1 deletion docs/modules/usage/how-to/gui-mode.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ The main interface consists of several key components:

## Tips for Effective Use

1. Be specific in your requests to get the most accurate and helpful responses, as described in the [prompting best practices](../prompting-best-practices).
1. Be specific in your requests to get the most accurate and helpful responses, as described in the [prompting best practices](../prompting/prompting-best-practices).
2. Use the workspace panel to explore your project structure.
3. Use one of the recommended models, as described in the [LLMs section](usage/llms/llms.md).

Expand Down
106 changes: 0 additions & 106 deletions docs/modules/usage/prompting-best-practices.md

This file was deleted.

67 changes: 67 additions & 0 deletions docs/modules/usage/prompting/customization.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# Customizing Agent Behavior

OpenHands can be customized to work more effectively with specific repositories by providing repository-specific context and guidelines. This section explains how to optimize OpenHands for your project.

## Repository Configuration

You can customize OpenHands' behavior for your repository by creating a `.openhands` directory in your repository's root. At minimum, it should contain the file
`.openhands/microagents/repo.md`, which includes instructions that will
be given to the agent every time it works with this repository.

We suggest including the following information:
1. **Repository Overview**: A brief description of your project's purpose and architecture
2. **Directory Structure**: Key directories and their purposes
3. **Development Guidelines**: Project-specific coding standards and practices
4. **Testing Requirements**: How to run tests and what types of tests are required
5. **Setup Instructions**: Steps needed to build and run the project

### Example Repository Configuration
Example `.openhands/microagents/repo.md` file:
```
Repository: MyProject
Description: A web application for task management

Directory Structure:
- src/: Main application code
- tests/: Test files
- docs/: Documentation

Setup:
- Run `npm install` to install dependencies
- Use `npm run dev` for development
- Run `npm test` for testing

Guidelines:
- Follow ESLint configuration
- Write tests for all new features
- Use TypeScript for new code
```

### Customizing Prompts

When working with a customized repository:

1. **Reference Project Standards**: Mention specific coding standards or patterns used in your project
2. **Include Context**: Reference relevant documentation or existing implementations
3. **Specify Testing Requirements**: Include project-specific testing requirements in your prompts

Example customized prompt:
```
Add a new task completion feature to src/components/TaskList.tsx following our existing component patterns.
Include unit tests in tests/components/ and update the documentation in docs/features/.
The component should use our shared styling from src/styles/components.
```

### Best Practices for Repository Customization

1. **Keep Instructions Updated**: Regularly update your `.openhands` directory as your project evolves
2. **Be Specific**: Include specific paths, patterns, and requirements unique to your project
3. **Document Dependencies**: List all tools and dependencies required for development
4. **Include Examples**: Provide examples of good code patterns from your project
5. **Specify Conventions**: Document naming conventions, file organization, and code style preferences

By customizing OpenHands for your repository, you'll get more accurate and consistent results that align with your project's standards and requirements.

## Other Microagents
You can create other instructions in the `.openhands/microagents/` directory
that will be sent to the agent if a particular keyword is found, like `test`, `frontend`, or `migration`. See [Microagents](microagents.md) for more information.
41 changes: 41 additions & 0 deletions docs/modules/usage/prompting/prompting-best-practices.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Prompting Best Practices

When working with OpenHands AI software developer, it's crucial to provide clear and effective prompts. This guide outlines best practices for creating prompts that will yield the most accurate and useful responses.

## Characteristics of Good Prompts

Good prompts are:

1. **Concrete**: They explain exactly what functionality should be added or what error needs to be fixed.
2. **Location-specific**: If known, they explain the locations in the code base that should be modified.
3. **Appropriately scoped**: They should be the size of a single feature, typically not exceeding 100 lines of code.

## Examples

### Good Prompt Examples

1. "Add a function `calculate_average` in `utils/math_operations.py` that takes a list of numbers as input and returns their average."

2. "Fix the TypeError in `frontend/src/components/UserProfile.tsx` occurring on line 42. The error suggests we're trying to access a property of undefined."

3. "Implement input validation for the email field in the registration form. Update `frontend/src/components/RegistrationForm.tsx` to check if the email is in a valid format before submission."

### Bad Prompt Examples

1. "Make the code better." (Too vague, not concrete)

2. "Rewrite the entire backend to use a different framework." (Not appropriately scoped)

3. "There's a bug somewhere in the user authentication. Can you find and fix it?" (Lacks specificity and location information)

## Tips for Effective Prompting

1. Be as specific as possible about the desired outcome or the problem to be solved.
2. Provide context, including relevant file paths and line numbers if available.
3. Break down large tasks into smaller, manageable prompts.
4. Include any relevant error messages or logs.
5. Specify the programming language or framework if it's not obvious from the context.

Remember, the more precise and informative your prompt is, the better the AI can assist you in developing or modifying the OpenHands software.

See [Getting Started with OpenHands](../getting-started) for more examples of helpful prompts.
11 changes: 8 additions & 3 deletions docs/sidebars.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,17 @@ const sidebars: SidebarsConfig = {
{
type: 'doc',
label: 'Best Practices',
id: 'usage/prompting-best-practices',
id: 'usage/prompting/prompting-best-practices',
},
{
type: 'doc',
label: 'Micro-Agents',
id: 'usage/micro-agents',
label: 'Customization',
id: 'usage/prompting/customization',
},
{
type: 'doc',
label: 'Microagents',
id: 'usage/prompting/microagents',
},
],
},
Expand Down
5 changes: 5 additions & 0 deletions openhands/agenthub/codeact_agent/prompts/system_prompt.j2
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,8 @@ You are OpenHands agent, a helpful AI assistant that can interact with a compute
* When configuring git credentials, use "openhands" as the user.name and "[email protected]" as the user.email by default, unless explicitly instructed otherwise.
* The assistant MUST NOT include comments in the code unless they are necessary to describe non-obvious behavior.
</IMPORTANT>
{% if repo_instructions %}
<REPOSITORY_INSTRUCTIONS>
{{ repo_instructions }}
</REPOSITORY_INSTRUCTIONS>
{% endif %}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As a side note, i think it probably makes more sense to add repository instructions in the first USER message rather than system message, which is typically used to define the behavior of LLM?

5 changes: 2 additions & 3 deletions openhands/runtime/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,12 +225,11 @@ def get_custom_microagents(self, selected_repository: str | None) -> list[str]:
dir_name = str(
Path(selected_repository.split('/')[1]) / custom_microagents_dir
)
oh_instructions_header = '---\nname: openhands_instructions\nagent: CodeActAgent\ntriggers:\n- ""\n---\n'
obs = self.read(FileReadAction(path='.openhands_instructions'))
if isinstance(obs, ErrorObservation):
self.log('error', 'Failed to read openhands_instructions')
self.log('debug', 'openhands_instructions not present')
else:
openhands_instructions = oh_instructions_header + obs.content
openhands_instructions = obs.content
self.log('info', f'openhands_instructions: {openhands_instructions}')
custom_microagents_content.append(openhands_instructions)

Expand Down
14 changes: 7 additions & 7 deletions openhands/utils/microagent.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@


class MicroAgentMetadata(pydantic.BaseModel):
name: str
agent: str
name: str = 'default'
agent: str = ''
triggers: list[str] = []


Expand All @@ -17,12 +17,12 @@ def __init__(self, path: str | None = None, content: str | None = None):
if not os.path.exists(path):
raise FileNotFoundError(f'Micro agent file {path} is not found')
with open(path, 'r') as file:
self._loaded = frontmatter.load(file)
self._content = self._loaded.content
self._metadata = MicroAgentMetadata(**self._loaded.metadata)
loaded = frontmatter.load(file)
self._content = loaded.content
self._metadata = MicroAgentMetadata(**loaded.metadata)
elif content and not path:
self._metadata, self._content = frontmatter.parse(content)
self._metadata = MicroAgentMetadata(**self._metadata)
metadata, self._content = frontmatter.parse(content)
self._metadata = MicroAgentMetadata(**metadata)
else:
raise Exception('You must pass either path or file content, but not both.')

Expand Down
9 changes: 8 additions & 1 deletion openhands/utils/prompt.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,14 @@ def _load_template(self, template_name: str) -> Template:
return Template(file.read())

def get_system_message(self) -> str:
return self.system_template.render().strip()
repo_instructions = ''
for microagent in self.microagents.values():
# We assume these are the repo instructions
if len(microagent.triggers) == 0:
if repo_instructions:
repo_instructions += '\n\n'
repo_instructions += microagent.content
return self.system_template.render(repo_instructions=repo_instructions).strip()

def get_example_user_message(self) -> str:
"""This is the initial user message provided to the agent
Expand Down
Loading