CodeScribe is not just a code generator; it's an advanced AI programming assistant that runs inside your Python REPL. It features multi-turn conversational capabilities and can autonomously use external tools (like documentation search) to solve complex problems, providing a seamless and intelligent coding experience.
- Real AI Conversations: Powered by powerful OpenAI models (like GPT-4/5), enabling it to understand complex context and engage in meaningful technical dialogues.
- Autonomous Tool Use (MCP):
CodeScribecan decide when it needs to look up external knowledge. For example, when asked about a specific library usage, it can automatically call thedeepwikitool to fetch the latest API documentation and then generate code based on that information. - Advanced Context-Awareness: Intelligently captures your local code context. It not only sees variables but also leverages
readlineto access your command history in standard Python REPLs (in addition to IPython/Jupyter), providing highly relevant and history-aware suggestions. - Interactive & Concise Code Suggestions: The returned code isn't just static text. It's an interactive object containing a detailed explanation and concise, to-the-point code. You can directly
.run()the code,.copy()it, use.ask()for follow-up questions, or.save()it to a file. - Intelligent File Saving: The
.save()method does more than just write to a file. It appends code, remembers your last used filename, and can optionally invokeruffto check for syntax errors. If issues are found, it can even ask the AI to correct them, helping you maintain clean, valid code. - Flexible Configuration: You can easily configure
CodeScribeto use different OpenAI models, API endpoints (Base URL), or custom MCP tools. - Error Analysis: Use the
.check_error()method to quickly get an explanation and a suggested fix for the last error that occurred in your REPL. - Automatic Exception Analysis: Go beyond reactive error checking.
CodeScribecan automatically analyze exceptions as they happen inside atry...exceptblock. You can choose to get an immediate, blocking analysis or let it run in the background and log the results to a file, so your interactive session is never interrupted.
pip install codescribe openaiBefore you begin, ensure you have set your OpenAI API key. CodeScribe will automatically read it from the OPENAI_API_KEY environment variable.
export OPENAI_API_KEY='your_openai_api_key'This example demonstrates how CodeScribe uses a tool automatically to help you complete a task.
from codescribe import CodeScribe
import pandas as pd
# Initialize the assistant
# You can also customize the model or API URL:
# scribe = CodeScribe(model="gpt-5-turbo", base_url="https://api.example.com/v1")
scribe = CodeScribe()
# Create a DataFrame in your global scope
data = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data)
# --- Step 1: Ask a question ---
# The user's request is a bit vague and might require looking up documentation
suggestion = scribe.ask("How should I save my DataFrame 'df' to a CSV file following best practices?")
# > 🤖 [CodeScribe is thinking...]
# > 🤖 [CodeScribe is automatically using tool: search_deepwiki]
# > 🤖 [CodeScribe is thinking...]
# --- Step 2: Get the final suggestion ---
# After calling the tool, CodeScribe returns the final suggestion,
# complete with an explanation and the code.
print(suggestion)
# > [CodeScribe Suggestion]
# > ---------------------------
# >
# > Based on the documentation, the best practice for saving a pandas DataFrame to CSV is to use the `to_csv` method and specify `index=False` to prevent writing the DataFrame index as a column in the file. This is generally the desired behavior.
# >
# > ```python
# > df.to_csv('output.csv', index=False)
# > ```
# >
# > Available actions:
# > - .run() : Execute the code.
# > - .copy() : Copy to clipboard.
# > - .save() : Save to a file.
# > - .ask(prompt): Ask a follow-up question.
# --- Step 3: Ask a follow-up question ---
follow_up = suggestion.ask("How can I append to the file instead?")
print(follow_up)
# > [CodeScribe Suggestion]
# > ---------------------------
# >
# > To append to a CSV file instead of overwriting it, you can use `mode='a'` and `header=False`.
# >
# > ```python
# > df.to_csv('output.csv', mode='a', index=False, header=False)
# > ```
# >
# > ...
### Intelligent File Saving with `.save()`
The `.save()` method makes it easy to persist your generated code. It's designed to be interactive and helpful.
```python
# --- Step 4: Save the code to a file ---
# If you run .save() without a filename, it will prompt you.
suggestion.save()
# > Enter filename: my_script.py
# > ✅ Code appended to 'my_script.py' (starting at line 1).
# It also remembers the last filename you used.
# If you save another suggestion, it will ask if you want to reuse it.
another_suggestion.save()
# > Use previous filename 'my_script.py'? (y/n): y
# > ✅ Code appended to 'my_script.py' (starting at line 5).
# After saving, it can check for syntax errors using `ruff`.
# > Check for Python syntax errors with ruff? (y/n): y
# > 🤖 [CodeScribe is running ruff...]
# If an error is found (like incorrect indentation), it can even try to fix it for you.
# > Potential syntax issues found:
# > my_script.py:6:1: E999 IndentationError: unindent does not match any outer indentation level
# > Attempt to fix indentation automatically? (y/n): y
# > 🤖 [CodeScribe is thinking...]
# > ✅ Indentation corrected and file saved.You can use scribe.analyze_exception(e) inside a try...except block to get instant analysis of an error.
try:
x = 100
y = "hello"
z = x + y
except Exception as e:
# Get an immediate, blocking analysis and print the suggestion
suggestion = scribe.analyze_exception(e)
if suggestion:
print(suggestion)
# The original exception can still be raised if needed
# raise e
# > 🤖 [CodeScribe] Analyzing exception...
# > 🤖 [CodeScribe is thinking...]
# > [CodeScribe Suggestion]
# > ---------------------------
# >
# > The error `TypeError: unsupported operand type(s) for +: 'int' and 'str'` occurs because you are trying to add an integer (`x`) to a string (`y`). In Python, these types cannot be concatenated with the `+` operator. To fix this, you should convert the integer to a string before adding them.
# >
# > ```python
# > z = str(x) + y
# > ```
# > ...
# --- For non-blocking analysis, use the `threaded=True` flag ---
# This is ideal for loops or long-running tasks.
# Configure scribe with a log file to see the results.
scribe_threaded = CodeScribe(exception_log_file="scribe_exceptions.log")
try:
# Some operation that might fail
result = 1 / 0
except Exception as e:
# This call returns immediately. The analysis runs in a background thread.
scribe_threaded.analyze_exception(e, threaded=True)
print("Analysis is running in the background. Check 'scribe_exceptions.log' for the result.")
# > [CodeScribe] Analyzing exception in the background...
# > Analysis is running in the background. Check 'scribe_exceptions.log' for the result.