How to use Cursor AI
Quick answer
Use
Cursor AI by integrating its Python SDK or API to enable AI-assisted code generation and completion. Typically, you install the cursor-python package, set your API key via environment variables, and call its client methods to generate or complete code snippets.PREREQUISITES
Python 3.8+Cursor AI API keypip install cursor-python
Setup
Install the official cursor-python SDK and set your API key as an environment variable for authentication.
pip install cursor-python Step by step
Use the Cursor client to generate code completions by providing prompts. Below is a complete example demonstrating initialization and a simple code generation call.
import os
from cursor import Cursor
# Initialize client with API key from environment
client = Cursor(api_key=os.environ["CURSOR_API_KEY"])
# Define a prompt for code generation
prompt = "Write a Python function to reverse a string."
# Call the generate_code method
response = client.generate_code(prompt=prompt, max_tokens=100)
# Print the generated code
print(response.generated_code) output
def reverse_string(s):
return s[::-1] Common variations
- Use async calls if supported by the SDK for non-blocking code generation.
- Adjust
max_tokensortemperatureparameters to control output length and creativity. - Switch models if Cursor AI offers multiple code generation models.
import asyncio
from cursor import Cursor
async def async_generate():
client = Cursor(api_key=os.environ["CURSOR_API_KEY"])
prompt = "Generate a Python class for a linked list."
response = await client.generate_code_async(prompt=prompt, max_tokens=150)
print(response.generated_code)
asyncio.run(async_generate()) output
class LinkedList:
def __init__(self):
self.head = None
# Additional linked list methods... Troubleshooting
- If you get authentication errors, verify your
CURSOR_API_KEYenvironment variable is set correctly. - For timeout or network issues, check your internet connection and retry.
- If code generation results are incomplete, increase
max_tokensor adjusttemperature.
Key Takeaways
- Install the official
cursor-pythonSDK and set your API key via environment variables. - Use
client.generate_code()for synchronous code generation with customizable parameters. - Async generation is available for non-blocking workflows if supported by the SDK.
- Adjust
max_tokensandtemperatureto control output length and creativity. - Verify API key and network connectivity to troubleshoot common errors.