{"id":28478816,"url":"https://github.com/civai-technologies/cursor-agent","last_synced_at":"2025-07-03T09:31:18.316Z","repository":{"id":283867291,"uuid":"953109210","full_name":"civai-technologies/cursor-agent","owner":"civai-technologies","description":"A Python-based AI agent that replicates Cursor's coding assistant capabilities, enabling function calling, code generation, and intelligent coding assistance with Claude, OpenAI, and locally hosted Ollama models.","archived":false,"fork":false,"pushed_at":"2025-06-06T11:14:45.000Z","size":463,"stargazers_count":30,"open_issues_count":0,"forks_count":13,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-06-07T18:07:18.278Z","etag":null,"topics":["agent","ai","civai","coding","cursor","cursor-agent-tools","framework","python"],"latest_commit_sha":null,"homepage":"https://civai.co","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/civai-technologies.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":"CODEOWNERS","security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"custom":["https://donate.stripe.com/3cIdR98sp40Xb2ydeyf7i0d"]}},"created_at":"2025-03-22T15:36:55.000Z","updated_at":"2025-06-06T11:14:47.000Z","dependencies_parsed_at":"2025-04-11T11:37:15.205Z","dependency_job_id":"b4aedb16-a934-4119-acc1-dbfff05f4e44","html_url":"https://github.com/civai-technologies/cursor-agent","commit_stats":null,"previous_names":["civai-technologies/cursor-agent"],"tags_count":12,"template":false,"template_full_name":null,"purl":"pkg:github/civai-technologies/cursor-agent","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/civai-technologies%2Fcursor-agent","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/civai-technologies%2Fcursor-agent/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/civai-technologies%2Fcursor-agent/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/civai-technologies%2Fcursor-agent/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/civai-technologies","download_url":"https://codeload.github.com/civai-technologies/cursor-agent/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/civai-technologies%2Fcursor-agent/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":263300190,"owners_count":23445196,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["agent","ai","civai","coding","cursor","cursor-agent-tools","framework","python"],"created_at":"2025-06-07T18:07:12.795Z","updated_at":"2025-07-03T09:31:18.307Z","avatar_url":"https://github.com/civai-technologies.png","language":"Python","funding_links":["https://donate.stripe.com/3cIdR98sp40Xb2ydeyf7i0d"],"categories":["Terminal-native coding agents"],"sub_categories":["Open Source"],"readme":"# Cursor Agent Tools\n\n![License](https://img.shields.io/github/license/civai-technologies/cursor-agent)\n![Python Version](https://img.shields.io/badge/python-3.8%2B-blue)\n![Anthropic](https://img.shields.io/badge/Anthropic-Claude-blueviolet)\n![OpenAI](https://img.shields.io/badge/OpenAI-GPT4-green)\n![Ollama](https://img.shields.io/badge/Ollama-Local%20Models-orange)\n\nA Python-based AI agent that replicates Cursor's coding assistant capabilities, enabling function calling, code generation, and intelligent coding assistance with Claude, OpenAI, and locally hosted Ollama models.\n\n## 🌟 Features\n\nThis AI Agent implementation provides a comprehensive set of capabilities:\n\n### Core Abilities\n\n- **Model Flexibility**: Works with Claude (Anthropic), OpenAI models, and locally hosted Ollama models\n- **Code Generation**: Generate complete, functional code based on natural language descriptions\n- **Code Editing**: Make precise edits to existing code files\n- **Code Analysis**: Review and analyze code for bugs, improvements, and optimizations\n- **Function Calling**: Invoke registered tools and functions based on user requests\n- **Conversational Context**: Maintain a conversation history for coherent back-and-forth interactions\n- **Project-Aware Responses**: Consider project context when answering questions\n- **Permission System**: Secure permission handling for file operations and command execution\n- **Local Model Support**: Use open-source models hosted locally with Ollama\n\n### Tool Functions\n\nThe agent supports a comprehensive set of tools:\n\n- **File Operations**:\n  - **read_file**: Read file contents with flexible line range control\n  - **edit_file**: Make precise edits to files with clear instructions\n    - Supports complete file replacement\n    - Supports line-based editing with JSON dictionaries (e.g., `{\"1-5\": \"new content\", \"10-12\": \"more content\"}`)\n  - **delete_file**: Remove files from the filesystem\n  - **create_file**: Create new files with specified content\n  - **list_dir**: List directory contents to understand project structure\n\n- **Search Capabilities**:\n  - **codebase_search**: Semantic search of codebases to find relevant code snippets\n  - **grep_search**: Perform regex-based text search in files\n  - **file_search**: Fuzzy search for files by name\n  - **web_search**: Search the web for up-to-date information\n  - **trend_search**: Search for trending topics and their latest developments\n\n- **Image Analysis**:\n  - **query_images**: Analyze and describe images using LLM vision capabilities\n\n- **System Operations**:\n  - **run_terminal_cmd**: Execute terminal commands with user approval\n\nAll tools are implemented with actual functionality and can be extended with custom tools as needed.\n\n## 📚 Table of Contents\n\n- [Installation](#installation)\n- [Quick Start](#quick-start)\n- [Usage Examples](#usage-examples)\n- [Project Structure](#project-structure)\n- [Configuration](#configuration)\n- [Permission System](#permission-system)\n- [Contributing](#contributing)\n- [API Documentation](#api-documentation)\n- [Advanced Usage](#advanced-usage)\n- [Limitations and Considerations](#limitations-and-considerations)\n- [Roadmap](#roadmap)\n- [License](#license)\n- [Acknowledgements](#acknowledgements)\n\n## 🚀 Installation\n\n### Prerequisites\n\n- Python 3.8+\n- API keys for Anthropic and/or OpenAI\n\n### Via pip\n\n```bash\npip install cursor-agent-tools\n```\n\n### From Source\n\n```bash\ngit clone https://github.com/civai-technologies/cursor-agent.git\ncd cursor-agent\npip install -e .  # Install in development mode\n\n# Or with development dependencies\npip install -e \".[dev]\"\n```\n\n### Environment Setup\n\nCreate a `.env` file in your project root (copy from `.env.example`):\n\n```ini\n# Environment (local, development, production)\nENVIRONMENT=local\n\n# OpenAI configuration\nOPENAI_API_KEY=your_openai_api_key_here\nOPENAI_API_MODEL=gpt-4o\nOPENAI_TEMPERATURE=0.0\n\n# Anthropic configuration\nANTHROPIC_API_KEY=your_anthropic_api_key_here\nANTHROPIC_API_MODEL=claude-3-5-sonnet-latest\nANTHROPIC_TEMPERATURE=0.0\n\n# Google Search API (for web_search tool)\nGOOGLE_API_KEY=your_google_api_key_here\nGOOGLE_SEARCH_ENGINE_ID=your_search_engine_id_here\n\n# Ollama configuration (for local models)\nOLLAMA_HOST=http://localhost:11434\n```\n\n## ⚡ Quick Start\n\n```python\nimport asyncio\nfrom cursor_agent_tools import create_agent\n\nasync def main():\n    # Create a Claude agent instance\n    agent = create_agent(model='claude-3-5-sonnet-latest')\n    \n    # Chat with the agent\n    response = await agent.chat(\"Create a Python function to calculate Fibonacci numbers\")\n    print(response)\n\nif __name__ == \"__main__\":\n    asyncio.run(main())\n```\n\n## 🔍 Usage Examples\n\n### Chat with Different Models\n\n```python\nimport asyncio\nfrom cursor_agent_tools import create_agent\n\n# Use Claude\nclaude_agent = create_agent(model='claude-3-5-sonnet-latest')\nresponse = await claude_agent.chat(\"What's a good way to implement a cache in Python?\")\n\n# Use OpenAI\nopenai_agent = create_agent(model='gpt-4o')\nresponse = await openai_agent.chat(\"What's a good way to implement a cache in Python?\")\n\n# Use Ollama (local open-source model)\nollama_agent = create_agent(model='ollama-llama3')\nresponse = await ollama_agent.chat(\"What's a good way to implement a cache in Python?\")\n```\n\n### Using Local Ollama Models\n\n```python\nimport asyncio\nfrom cursor_agent_tools import create_agent\n\nasync def main():\n    # Create an agent with a local Ollama model\n    # Models must be pulled via Ollama CLI first: ollama pull MODEL_NAME\n    agent = create_agent(\n        model='ollama-llama3',  # prefix with \"ollama-\" followed by model name\n        host='http://localhost:11434',  # optional, this is the default\n        temperature=0.3  # optional temperature setting\n    )\n    \n    # Chat with the local model\n    response = await agent.chat(\"Write a Python script to download YouTube videos\")\n    print(response)\n    \n    # Handle multimodal capabilities if model supports it\n    # image_path = \"/path/to/your/image.png\"\n    # image_response = await agent.query_image(\n    #     image_paths=[image_path],\n    #     query=\"What does this code screenshot show?\"\n    # )\n    # print(image_response)\n\nif __name__ == \"__main__\":\n    asyncio.run(main())\n```\n\n### Supported Ollama Models\n\nThe agent supports any model available in Ollama. Some popular options include:\n\n- `ollama-llama3` - Meta's Llama 3 model\n- `ollama-llama3.1` - Meta's Llama 3.1 model\n- `ollama-mistral` - Mistral AI's model\n- `ollama-gemma3` - Google's Gemma model\n- `ollama-deepseek-r1` - DeepSeek's reasoning model\n- `ollama-phi4` - Microsoft's Phi model\n- `ollama-qwen2.5` - Qwen's latest model\n\nFor a complete list of available models, see [Ollama Library](https://ollama.com/library).\n\nNote that tool calling and multimodal support depend on the capabilities of the specific model.\n\n### Creating a Custom Agent with Custom System Prompt\n\n```python\nimport asyncio\nfrom cursor_agent_tools import create_agent\n\nasync def main():\n    # Define a custom system prompt for a coding tutor\n    custom_system_prompt = \"\"\"\n    You are an expert coding tutor specialized in helping beginners learn to code.\n    When asked coding questions:\n    1. First explain the concept in simple terms\n    2. Always provide commented example code\n    3. Suggest practice exercises\n    4. Anticipate common mistakes and warn against them\n    \n    Be patient, encouraging, and avoid technical jargon unless you explain it.\n    Focus on building good habits and understanding core principles.\n    \"\"\"\n    \n    # Create agent with custom system prompt\n    coding_tutor = create_agent(\n        model='claude-3-5-sonnet-latest',\n        system_prompt=custom_system_prompt\n    )\n    \n    # Example interaction with the custom agent\n    student_question = \"I'm confused about Python list comprehensions. Can you help me understand them?\"\n    \n    response = await coding_tutor.chat(student_question)\n    print(response)\n    \n    # Example using image analysis capabilities\n    image_path = \"/path/to/your/image.png\"\n    image_response = await coding_tutor.query_image(\n        image_paths=[image_path],\n        query=\"What does this code screenshot show and what issues do you see?\"\n    )\n    print(image_response)\n    \n    # The response will follow the guidelines in the custom system prompt,\n    # explaining list comprehensions in a beginner-friendly way with examples, \n    # practice exercises, and common pitfalls to avoid\n\nif __name__ == \"__main__\":\n    asyncio.run(main())\n```\n\nThis example creates a specialized coding tutor agent with a custom personality and behavior guidelines. You can similarly create custom agents for various domains by crafting appropriate system prompts:\n\n- Data analysis assistant (focusing on pandas/numpy)\n- DevOps automation expert (for CI/CD and deployment scripts)\n- Documentation writer (generating well-structured docs from code)\n- Security code reviewer (identifying vulnerabilities in code)\n- Algorithm optimization specialist (improving performance)\n\n### Interactive Mode\n\n```python\nfrom cursor_agent_tools import run_agent_interactive\nimport asyncio\n\nasync def main():\n    # Parameters:\n    # - model: The model to use (e.g., 'claude-3-5-sonnet-latest', 'gpt-4o')\n    # - initial_query: The task description\n    # - max_iterations: Maximum number of steps (default 10)\n    # - auto_continue: Whether to continue automatically without user input (default True)\n    \n    await run_agent_interactive(\n        model='claude-3-5-sonnet-latest',\n        initial_query='Create a simple web scraper that extracts headlines from a news website',\n        max_iterations=15\n        # auto_continue=True is the default - agent continues automatically\n        # To disable automatic continuation, set auto_continue=False\n    )\n\nif __name__ == \"__main__\":\n    asyncio.run(main())\n```\n\nThe interactive mode is designed to automatically continue without user interaction unless:\n1. The AI explicitly requests more information from the user\n2. An error occurs that requires user decision\n3. The `--auto` flag is used, which will prompt for user input after each step\n4. The maximum tool call limit is reached, prompting for user confirmation to continue\n\nWhen user input is requested or provided, the system intelligently incorporates this input into the conversation flow by:\n1. Using the AI model itself to generate a contextually appropriate continuation prompt\n2. Seamlessly integrating the user's input with the existing conversation history\n3. Maintaining the natural flow of the implementation process\n\n### Automatic User Input Detection\n\nThe interactive mode has built-in detection for when the agent is explicitly asking for user input. When the agent's response includes phrases like:\n- \"I need more information about...\"\n- \"Could you provide more details on...\"\n- \"Please let me know your preference for...\"\n- \"What would you like me to do about...\"\n\nThe system will automatically pause and wait for user input, even in auto-continue mode. This ensures that when the agent genuinely needs clarification or a decision from you, the conversation pauses appropriately.\n\n### Tool Call Limit Confirmation\n\nFor safety and to prevent runaway automation, the agent tracks the total number of tool calls made during processing a single agent response. When this count reaches a certain threshold (default: 5), the agent will request user confirmation before making more changes. This is a safeguard that:\n- Prevents unintended extensive changes to your codebase\n- Gives you visibility into complex operations\n- Allows you to review progress before continuing\n- Provides an opportunity to redirect the agent if needed\n\nImportant details about how tool call tracking works:\n- The counter tracks all tool calls within one logical iteration (one agent response)\n- The counter is NOT reset until new user input is provided or a new query is started\n- The counter persists even when the agent continues with the same iteration\n\nWhen the limit is reached, you'll be prompted with:\n```\nThe agent has made 5 tool calls in this iteration.\nWould you like to continue allowing the agent to make more changes?\nContinue? (y/n):\n```\n\nIf you approve, the agent will:\n- Continue making more tool calls in the current iteration\n- Increase the limit by 5 for this iteration\n- Ask for confirmation again when the new limit is reached\n- Keep tracking the total number of tool calls (the counter is not reset)\n\nIf you deny, the agent will:\n- Stop making additional tool calls for this iteration\n- Complete the current iteration with the changes already made\n- Continue to the next iteration when ready\n\nThis adaptive limit ensures the agent doesn't make too many changes without your approval, while still allowing complex tasks to be completed efficiently.\n\n### Providing Project Context\n\n```python\nfrom cursor_agent_tools import create_agent\n\nagent = create_agent(model='claude-3-5-sonnet-latest')\n\nuser_info = {\n    \"open_files\": [\"src/main.py\", \"src/utils.py\"],\n    \"cursor_position\": {\"file\": \"src/main.py\", \"line\": 42},\n    \"recent_files\": [\"src/config.py\", \"tests/test_main.py\"],\n    \"os\": \"darwin\",\n    \"workspace_path\": \"/Users/username/projects/myproject\"\n}\n\nresponse = await agent.chat(\"Fix the bug in the main function\", user_info=user_info)\n```\n\n### Custom Tool Registration\n\n```python\nfrom cursor_agent_tools import create_agent\n\nagent = create_agent(model='claude-3-5-sonnet-latest')\n\ndef custom_tool(param1, param2):\n    # Tool implementation\n    return {\"result\": f\"Processed {param1} and {param2}\"}\n\n# Register the tool\nagent.register_tool(\n    name=\"custom_tool\",\n    function=custom_tool,\n    description=\"Custom tool that does something useful\",\n    parameters={\n        \"properties\": {\n            \"param1\": {\"description\": \"First parameter\", \"type\": \"string\"},\n            \"param2\": {\"description\": \"Second parameter\", \"type\": \"string\"}\n        },\n        \"required\": [\"param1\", \"param2\"]\n    }\n)\n```\n\nFor more examples, check the [examples](examples/) directory.\n\n## 🏗️ Project Structure\n\n```\ncursor-agent/\n├── agent/                   # Core agent implementation\n│   ├── __init__.py          # Package exports\n│   ├── base.py              # Base agent class\n│   ├── claude_agent.py      # Claude-specific implementation\n│   ├── openai_agent.py      # OpenAI-specific implementation\n│   ├── factory.py           # Agent factory function\n│   ├── permissions.py       # Permission system implementation\n│   ├── interact.py          # Interactive mode utilities\n│   └── tools/               # Tool implementations\n│       ├── __init__.py      # Tool exports\n│       ├── file_tools.py    # File operations\n│       ├── search_tools.py  # Search functionalities\n│       ├── system_tools.py  # System commands\n│       └── register_tools.py # Tool registration utilities\n├── cursor_agent/            # Package directory for pip installation\n│   ├── __init__.py          # Package exports\n│   └── agent/               # Re-exports of agent functionality\n├── docs/                    # Documentation\n│   └── permissions_guide.md # Permission system documentation\n├── examples/                # Example usage scripts\n│   ├── basic_usage.py       # Simple API usage example\n│   ├── chat_conversation_example.py  # Conversation example\n│   ├── code_search_example.py  # Code search demonstration\n│   ├── file_manipulation_example.py  # File tools example\n│   ├── interactive_mode_example.py  # Interactive session demo\n│   ├── permission_example.py  # Permission system demonstration\n│   ├── simple_task_example.py  # Basic task completion\n│   ├── utils.py             # Example utilities\n│   └── demo_project/        # Demo project for examples\n├── tests/                   # Unit and integration tests\n│   ├── test_permissions.py  # Permission system tests\n│   └── ...                  # Other test files\n├── .env.example             # Example environment variables\n├── .gitignore               # Git ignore patterns\n├── CODE_OF_CONDUCT.md       # Code of conduct for contributors\n├── CONTRIBUTING.md          # Contribution guidelines\n├── LICENSE                  # MIT License\n├── README.md                # This file\n├── SECURITY.md              # Security policy\n├── constraints.md           # Implementation constraints\n├── pyproject.toml           # Project configuration\n├── requirements.txt         # Project dependencies\n├── run_tests.py             # Test runner script\n├── run_ci_checks.sh         # CI check script\n└── setup.py                 # Package installation\n```\n\n## ⚙️ Configuration\n\n### Environment Variables\n\n| Variable | Description | Default |\n|----------|-------------|---------|\n| `ANTHROPIC_API_KEY` | Anthropic API key for Claude | None |\n| `ANTHROPIC_API_MODEL` | Claude model to use | claude-3-5-sonnet-latest |\n| `ANTHROPIC_TEMPERATURE` | Claude temperature setting | 0.0 |\n| `OPENAI_API_KEY` | OpenAI API key | None |\n| `OPENAI_API_MODEL` | OpenAI model to use | gpt-4o |\n| `OPENAI_TEMPERATURE` | OpenAI temperature setting | 0.0 |\n| `ENVIRONMENT` | Environment mode | local |\n\n### Agent Configuration\n\nWhen creating an agent, you can customize its behavior:\n\n```python\nfrom cursor_agent_tools import create_agent\nfrom cursor_agent_tools.permissions import PermissionOptions\n\n# Create permission options\npermissions = PermissionOptions(\n    yolo_mode=True,\n    command_allowlist=[\"ls\", \"echo\", \"git\"],\n    command_denylist=[\"rm -rf\", \"sudo\"],\n    delete_file_protection=True\n)\n\nagent = create_agent(\n    model='claude-3-5-sonnet-latest',  # Specific model to use (determines the agent type)\n    temperature=0.2,                    # Creativity level\n    system_prompt=None,                 # Custom system prompt\n    tools=None,                         # Custom tools dictionary\n    permission_options=permissions      # Permission configuration\n)\n```\n\n## 🔐 Permission System\n\nThe CursorAgent includes a robust permission system for secure handling of system operations:\n\n### Key Features\n\n- **Secure by Default**: All file modifications and command executions require permission\n- **YOLO Mode**: Optional mode for automatic approval of operations (with configurable rules)\n- **Command Filtering**: Allowlist/denylist for controlling which commands can run automatically\n- **File Deletion Protection**: Special protection for file deletion operations\n- **Customizable UI**: Flexible permission request interface adaptable to different environments\n\n### Basic Usage\n\n```python\nfrom cursor_agent_tools import create_agent\nfrom cursor_agent_tools.permissions import PermissionOptions\n\n# Create an agent with default permissions (requires confirmation for all operations)\npermissions = PermissionOptions(yolo_mode=False)\nagent = create_agent(\n    model='claude-3-5-sonnet-latest',\n    permission_options=permissions\n)\n\n# Create an agent with YOLO mode (many operations auto-approved)\npermissions = PermissionOptions(\n    yolo_mode=True,\n    command_allowlist=[\"ls\", \"echo\", \"git\"],\n    delete_file_protection=True\n)\nagent = create_agent(\n    model='claude-3-5-sonnet-latest',\n    permission_options=permissions\n)\n```\n\n### Custom Permission Handlers\n\nThe permission system can be adapted to different UI environments:\n\n```python\nfrom cursor_agent_tools.permissions import PermissionOptions, PermissionRequest, PermissionStatus\n\n# Create a custom permission handler for a GUI application\ndef gui_permission_handler(request: PermissionRequest) -\u003e PermissionStatus:\n    # Implement GUI-based permission dialog\n    # ...\n    return PermissionStatus.GRANTED  # or DENIED\n\n# Create permission options with custom handler\npermissions = PermissionOptions(\n    yolo_mode=False,\n    permission_callback=gui_permission_handler\n)\n\nagent = create_agent(\n    model='claude-3-5-sonnet-latest',\n    permission_options=permissions\n)\n```\n\nFor comprehensive documentation on the permission system, see [permissions_guide.md](docs/permissions_guide.md).\n\n## 🤝 Contributing\n\nContributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details on how to contribute to this project.\n\n### Development Setup\n\n1. Fork and clone the repository\n2. Create a virtual environment\n3. Install development dependencies: `pip install -e \".[dev]\"`\n4. Set up API keys in a `.env` file\n5. Submit pull requests for features or fixes\n\n### Code Style\n\nWe use flake8 for linting. To ensure consistent style, please make sure your code:\n\n1. Passes the flake8 linting check with `flake8 cursor_agent_tools`\n2. Has no whitespace issues. You can use the included script to fix common whitespace issues:\n   ```\n   python fix_whitespace_errors.py\n   ```\n   This will automatically fix trailing whitespace (W291) and blank lines with whitespace (W293) in the cursor_agent_tools directory.\n\n## 📚 API Documentation\n\n### Agent Factory\n\n```python\n# Import the factory function\nfrom cursor_agent_tools import create_agent\n\ndef create_agent(\n    model: str,\n    temperature: Optional[float] = None,\n    system_prompt: Optional[str] = None,\n    tools: Optional[Dict] = None,\n) -\u003e BaseAgent:\n    \"\"\"\n    Create an agent instance based on the specified model.\n    \n    Args:\n        model: The model to use (e.g. 'claude-3-5-sonnet-latest', 'gpt-4o')\n        temperature: The temperature setting for generation\n        system_prompt: Custom system prompt to use\n        tools: Custom tools dictionary\n        \n    Returns:\n        An instance of BaseAgent (either ClaudeAgent or OpenAIAgent)\n    \"\"\"\n```\n\n### Base Agent Methods\n\n```python\n# Import necessary types\nfrom typing import Dict, List, Callable, Optional\nfrom cursor_agent_tools import BaseAgent\n\nclass BaseAgent:\n    async def chat(\n        self, user_message: str, user_info: Optional[Dict] = None\n    ) -\u003e str:\n        \"\"\"Send a message to the agent and get a response.\"\"\"\n        \n    def register_tool(\n        self, name: str, function: Callable, description: str, parameters: Dict\n    ) -\u003e None:\n        \"\"\"Register a custom tool with the agent.\"\"\"\n        \n    async def _prepare_tools(self) -\u003e Dict:\n        \"\"\"Prepare tools for the model's API format.\"\"\"\n        \n    async def _execute_tool_calls(self, tool_calls: List[Dict]) -\u003e List[Dict]:\n        \"\"\"Execute tool calls and return results.\"\"\"\n```\n\nFor complete API documentation, refer to the docstrings in the source code.\n\n## 🔧 Advanced Usage\n\n### Tool Implementation\n\nTools are Python functions registered with the agent. The cursor-agent library supports various types of tools to enhance your agent's capabilities:\n\n#### Basic Tool Registration\n\n```python\nfrom cursor_agent_tools import create_agent\n\nagent = create_agent(model='claude-3-5-sonnet-latest')\n\ndef database_query(query: str, connection_string: str):\n    \"\"\"Execute a database query and return results.\"\"\"\n    # Implementation...\n    return {\"results\": [...]}\n\nagent.register_tool(\n    name=\"database_query\",\n    function=database_query,\n    description=\"Execute a SQL query against a database\",\n    parameters={\n        \"properties\": {\n            \"query\": {\"description\": \"SQL query to execute\", \"type\": \"string\"},\n            \"connection_string\": {\"description\": \"Database connection string\", \"type\": \"string\"}\n        },\n        \"required\": [\"query\", \"connection_string\"]\n    }\n)\n```\n\n#### API Integration Tools\n\n```python\nfrom cursor_agent_tools import create_agent\nimport requests\n\nagent = create_agent(model='claude-3-5-sonnet-latest')\n\ndef fetch_weather(location: str, units: str = \"metric\"):\n    \"\"\"Fetch current weather data for a location.\"\"\"\n    API_KEY = \"your_api_key\"  # Better to use environment variables\n    url = f\"https://api.weatherapi.com/v1/current.json?key={API_KEY}\u0026q={location}\u0026units={units}\"\n    \n    response = requests.get(url)\n    if response.status_code == 200:\n        return response.json()\n    else:\n        return {\"error\": f\"API returned status code {response.status_code}\"}\n\nagent.register_tool(\n    name=\"fetch_weather\",\n    function=fetch_weather,\n    description=\"Get current weather data for a specified location\",\n    parameters={\n        \"properties\": {\n            \"location\": {\"description\": \"City name or coordinates\", \"type\": \"string\"},\n            \"units\": {\"description\": \"Units system (metric or imperial)\", \"type\": \"string\"}\n        },\n        \"required\": [\"location\"]\n    }\n)\n```\n\n#### Data Processing Tools\n\n```python\nfrom cursor_agent_tools import create_agent\nimport pandas as pd\nimport json\n\nagent = create_agent(model='claude-3-5-sonnet-latest')\n\ndef analyze_csv(file_path: str, operations: list):\n    \"\"\"Perform analytical operations on a CSV file.\"\"\"\n    try:\n        # Load the data\n        df = pd.read_csv(file_path)\n        \n        results = {}\n        for operation in operations:\n            if operation == \"summary\":\n                results[\"summary\"] = json.loads(df.describe().to_json())\n            elif operation == \"columns\":\n                results[\"columns\"] = df.columns.tolist()\n            elif operation == \"missing\":\n                results[\"missing\"] = json.loads(df.isnull().sum().to_json())\n                \n        return results\n    except Exception as e:\n        return {\"error\": str(e)}\n\nagent.register_tool(\n    name=\"analyze_csv\",\n    function=analyze_csv,\n    description=\"Analyze a CSV file with various statistical operations\",\n    parameters={\n        \"properties\": {\n            \"file_path\": {\"description\": \"Path to the CSV file\", \"type\": \"string\"},\n            \"operations\": {\n                \"description\": \"List of operations to perform\",\n                \"type\": \"array\",\n                \"items\": {\"type\": \"string\"}\n            }\n        },\n        \"required\": [\"file_path\", \"operations\"]\n    }\n)\n```\n\n### File Operations Examples\n\n#### Line-Based File Editing\n\nThe agent supports precise editing of files using line numbers:\n\n```python\nimport json\nfrom cursor_agent_tools import create_agent\n\nasync def main():\n    agent = create_agent(model='claude-3-5-sonnet-latest')\n    \n    # Define line-based edits as a dictionary with line ranges as keys\n    line_edits = {\n        \"5-8\": \"def calculate_total(items):\\n    \\\"\\\"\\\"Calculate the total price of all items.\\\"\\\"\\\"\\n    return sum(item.price for item in items)\\n\",\n        \"12-12\": \"    # Log the transaction\\n    logging.info(f\\\"Processed order: {order_id}\\\")\\n\"\n    }\n    \n    # Convert to JSON string for the edit_file function\n    code_edit_json = json.dumps(line_edits)\n    \n    # Apply edits to specific line ranges\n    await agent.edit_file(\n        target_file=\"/path/to/your/file.py\",\n        instructions=\"Update calculate_total function and add logging\",\n        code_edit=code_edit_json\n    )\n\nif __name__ == \"__main__\":\n    asyncio.run(main())\n```\n\nThis approach has several advantages:\n- Precisely target specific line ranges for editing\n- Make multiple edits in a single operation\n- Clear and structured format for programmatic editing\n- Easier to automate and script file modifications\n\nFor more examples, check out [line_based_edit_example.py](examples/line_based_edit_example.py).\n\n### Providing Project Context\n\n```python\nfrom cursor_agent_tools import create_agent\n\nagent = create_agent(model='claude-3-5-sonnet-latest')\n\nuser_info = {\n    \"open_files\": [\"src/main.py\", \"src/utils.py\"],\n    \"cursor_position\": {\"file\": \"src/main.py\", \"line\": 42},\n    \"recent_files\": [\"src/config.py\", \"tests/test_main.py\"],\n    \"os\": \"darwin\",\n    \"workspace_path\": \"/Users/username/projects/myproject\"\n}\n\nresponse = await agent.chat(\"Fix the bug in the main function\", user_info=user_info)\n```\n\n## ⚠️ Limitations and Considerations\n\n- **API Key Security**: Keep your API keys secure and never commit them to repositories\n- **Context Windows**: Models have token limits that restrict the amount of code they can process\n- **Tool Execution**: Function calling executes code on your system - implement proper security\n- **Rate Limits**: APIs have rate limits that may restrict usage\n- **Costs**: Using the APIs incurs costs based on token usage\n\nFor a detailed list of constraints and workarounds, see the [constraints.md](constraints.md) file.\n\n## 🛣️ Roadmap\n\n- Streaming responses\n- Support for more model families (e.g., Gemini, Llama, etc.)\n- Web interface\n- Multi-user support with authentication\n- Vector-based codebase search\n- Testing tools integration\n- Comprehensive demo suite\n- Documentation website\n\n## 📜 License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## 🙏 Acknowledgements\n\n- [Anthropic](https://www.anthropic.com/) for the Claude API\n- [OpenAI](https://openai.com/) for the OpenAI API\n- [Cursor](https://cursor.sh/) for inspiration\n\n## 👤 Author\n\nFemi Amoo (Nifemi Alpine)\n\nFounder of [CIVAI TECHNOLOGIES](https://civai.co)\n\n[![Twitter](https://img.shields.io/twitter/follow/usecodenaija?style=social)](https://twitter.com/usecodenaija) ","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcivai-technologies%2Fcursor-agent","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcivai-technologies%2Fcursor-agent","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcivai-technologies%2Fcursor-agent/lists"}