Of course. This is a fascinating and powerful use case for a local LLM. Here is a complete Python script that automates the process of fixing "target uri doesn't exist" errors in a Flutter project.
Pre-requisites
- Python 3: Ensure you have Python installed.
- Required Python Libraries: You'll need
requests to talk to the LLM and PyYAML to safely edit the pubspec.yaml file.
pip install requests pyyaml
- Flutter SDK: The script assumes
flutter is in your system's PATH. You need it to run flutter analyze and flutter pub get.
- LM Studio:
- Download and install LM Studio.
- Download a model suitable for coding tasks (e.g., Code Llama, Mistral, etc.).
- Go to the "Local Server" tab (looks like
<-->).
- Select your model and click "Start Server".
- The script will use the default endpoint:
http://localhost:1234/v1/chat/completions.
The Python Script: flutter_doctor_llm.py
This script is designed to be run from your terminal. It will:
- Continuously run
flutter analyze.
- Parse the output to find
uri_does_not_exist errors.
- Take the first error found and extract the missing import URI.
- Send a carefully crafted prompt to your local LM Studio instance to ask for the correct package name.
- Add the package to
pubspec.yaml under dependencies.
- Run
flutter pub get.
- Repeat the whole process until no more
uri_does_not_exist errors are found.
import os
import sys
import subprocess
import re
import requests
import yaml
import time
# --- CONFIGURATION ---
# The API endpoint for your local LM Studio server.
LM_STUDIO_URL = "http://localhost:1234/v1/chat/completions"
# --- HELPER FUNCTIONS ---
def run_command(command, cwd):
"""Executes a command in a given directory and returns its output."""
print(f"\n> Running command: {' '.join(command)}")
try:
result = subprocess.run(
command,
cwd=cwd,
capture_output=True,
text=True,
check=False # Don't raise exception for non-zero exit codes
)
if result.returncode != 0:
print(f" Warning: Command exited with code {result.returncode}")
# Even with an error, stdout/stderr might have useful info
return result.stdout, result.stderr
except FileNotFoundError:
print(f"Error: Command '{command[0]}' not found.")
print("Please ensure the Flutter SDK is in your system's PATH.")
sys.exit(1)
except Exception as e:
print(f"An unexpected error occurred while running command: {e}")
sys.exit(1)
def find_analysis_errors(project_path):
"""Runs 'flutter analyze' and parses for 'uri_does_not_exist' errors."""
stdout, stderr = run_command(['flutter', 'analyze'], cwd=project_path)
output = stdout + stderr
# Regex to find: error • Target of URI doesn't exist: 'package:http/http.dart' • lib/main.dart:2:8 • uri_does_not_exist
error_pattern = re.compile(r"Target of URI doesn't exist: '([^']+)'.*uri_does_not_exist")
found_errors = []
for line in output.splitlines():
match = error_pattern.search(line)
if match:
uri = match.group(1)
print(f" [!] Found missing URI: {uri}")
found_errors.append({'uri': uri})
return found_errors
def ask_llm_for_package(import_uri):
"""Asks the LLM what package corresponds to a given import URI."""
prompt = f"""
A Flutter app has a missing import: '{import_uri}'.
What is the name of the dependency I need to add to my pubspec.yaml file to fix this?
Respond with ONLY the package name and nothing else. For example, if the import is 'package:http/http.dart', you should respond with 'http'.
"""
print(f"\n> Asking LLM for package name for '{import_uri}'...")
headers = {"Content-Type": "application/json"}
payload = {
"model": "local-model", # This is a placeholder, LM Studio ignores it
"messages": [
{"role": "system", "content": "You are a helpful expert on Flutter and Dart dependencies."},
{"role": "user", "content": prompt}
],
"temperature": 0.1, # Low temperature for deterministic answers
}
try:
response = requests.post(LM_STUDIO_URL, headers=headers, json=payload, timeout=60)
response.raise_for_status()
data = response.json()
package_name = data['choices'][0]['message']['content'].strip().lower()
# Clean up potential LLM verbosity
package_name = re.split(r'\s|:', package_name)[0]
print(f" [+] LLM suggested package: '{package_name}'")
return package_name
except requests.exceptions.RequestException as e:
print(f"\nError connecting to LM Studio at {LM_STUDIO_URL}.")
print("Please ensure LM Studio is running and the server is started.")
print(f"Details: {e}")
return None
except (KeyError, IndexError) as e:
print(f"Error parsing LLM response: {e}")
print(f"Raw response: {response.text}")
return None
def add_dependency_to_pubspec(package_name, pubspec_path):
"""Adds a package to pubspec.yaml if it doesn't already exist."""
print(f"\n> Attempting to add '{package_name}' to {pubspec_path}...")
try:
with open(pubspec_path, 'r') as f:
pubspec_data = yaml.safe_load(f)
if 'dependencies' not in pubspec_data:
pubspec_data['dependencies'] = {}
if package_name in pubspec_data['dependencies']:
print(f" [*] Package '{package_name}' already exists in dependencies. Skipping.")
return False
# Add the package with 'any' version specifier
pubspec_data['dependencies'][package_name] = 'any'
with open(pubspec_path, 'w') as f:
yaml.dump(pubspec_data, f, default_flow_style=False, sort_keys=False)
print(f" [+] Successfully added '{package_name}: any' to dependencies.")
return True
except FileNotFoundError:
print(f"Error: pubspec.yaml not found at {pubspec_path}")
return False
except Exception as e:
print(f"Error updating pubspec.yaml: {e}")
return False
def main():
"""Main execution loop."""
if len(sys.argv) < 2:
print("Usage: python flutter_doctor_llm.py <path_to_flutter_project>")
sys.exit(1)
project_path = sys.argv[1]
pubspec_path = os.path.join(project_path, 'pubspec.yaml')
if not os.path.isdir(project_path) or not os.path.exists(pubspec_path):
print(f"Error: Provided path '{project_path}' is not a valid Flutter project directory.")
sys.exit(1)
print(f"--- Starting Auto-Dependency Fixer for '{project_path}' ---")
# Keep track of URIs we've already tried to fix to prevent infinite loops
processed_uris = set()
while True:
errors = find_analysis_errors(project_path)
if not errors:
print("\n✅ All 'uri_does_not_exist' errors are resolved. Exiting.")
break
# Get the first unprocessed error
current_error = None
for error in errors:
if error['uri'] not in processed_uris:
current_error = error
break
if not current_error:
print("\n❌ No new errors to process, but some still exist.")
print("This could mean the LLM suggested a wrong package or there's another issue.")
print("Please review the remaining errors manually. Exiting.")
break
uri_to_fix = current_error['uri']
processed_uris.add(uri_to_fix) # Mark as processed
package_name = ask_llm_for_package(uri_to_fix)
if not package_name:
print("\n❌ Could not get package name from LLM. Aborting.")
break
was_added = add_dependency_to_pubspec(package_name, pubspec_path)
if was_added:
# Dependency was added, now run pub get
stdout, stderr = run_command(['flutter', 'pub', 'get'], cwd=project_path)
if "resolving dependencies" not in stdout and "Got dependencies" not in stdout:
print("\n❌ 'flutter pub get' may have failed. Check output above. Aborting.")
print("--- Stderr ---")
print(stderr)
break
print("\n--- Re-analyzing project... ---")
time.sleep(2) # Brief pause
if __name__ == "__main__":
main()
How to Use
-
Save the Script: Save the code above as a file named flutter_doctor_llm.py.
-
Start LM Studio Server: Make sure your local LM Studio server is running.
-
Navigate to a Test Project: Create a simple Flutter project for testing. For example, create a new project and add a problematic import to lib/main.dart:
// lib/main.dart
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http; // This line will cause the error
import 'package:provider/provider.dart'; // This one too
void main() {
runApp(const MyApp());
}
// ... rest of the default code
Ensure you do not have http or provider in your pubspec.yaml yet.
-
Run the Script: Open your terminal, cd to a directory outside your Flutter project, and run the script, passing the path to your project as an argument.
# If the script is in your current directory and your project is in a folder named 'my_flutter_app'
python flutter_doctor_llm.py ./my_flutter_app
# Or provide an absolute path
# python flutter_doctor_llm.py /path/to/your/flutter/project
Example Walkthrough
When you run the script on the broken project, you will see output like this in your terminal:
--- Starting Auto-Dependency Fixer for './my_flutter_app' ---
> Running command: flutter analyze
[!] Found missing URI: package:http/http.dart
[!] Found missing URI: package:provider/provider.dart
> Asking LLM for package name for 'package:http/http.dart'...
[+] LLM suggested package: 'http'
> Attempting to add 'http' to ./my_flutter_app/pubspec.yaml...
[+] Successfully added 'http: any' to dependencies.
> Running command: flutter pub get
Resolving dependencies...
+ http 1.1.0 (1.2.1 available)
... (pub get output) ...
Got dependencies!
--- Re-analyzing project... ---
> Running command: flutter analyze
[!] Found missing URI: package:provider/provider.dart
> Asking LLM for package name for 'package:provider/provider.dart'...
[+] LLM suggested package: 'provider'
> Attempting to add 'provider' to ./my_flutter_app/pubspec.yaml...
[+] Successfully added 'provider: any' to dependencies.
> Running command: flutter pub get
Resolving dependencies...
+ provider 6.0.5 (6.1.1 available)
... (pub get output) ...
Got dependencies!
--- Re-analyzing project... ---
> Running command: flutter analyze
Analyzing my_flutter_app...
No issues found!
✅ All 'uri_does_not_exist' errors are resolved. Exiting.
Your pubspec.yaml will now have been automatically updated.