This project is a C# console application that leverages Google's Gemini AI to generate and execute C# code snippets dynamically based on user input. It allows users to type a natural language instruction, which is then sent to the AI to produce a simple C# script. This script is subsequently run directly within the terminal.
- AI-Powered Code Generation: Integrates with Google's Gemini AI (specifically the
gemini-2.0-flash
model) to generate C# code. - Dynamic Execution: Utilizes Roslyn's
Microsoft.CodeAnalysis.CSharp.Scripting
library to execute the AI-generated C# code on the fly. - Interactive Console: Takes user input directly from the terminal to form the basis of the AI prompt.
- JSON Parsing: Handles the JSON response from the Gemini API to extract the generated code.
- Simplified Scripting: Instructs the AI to produce C# code that is script-like (no namespaces, classes, or
Main
method required for execution viaCSharpScript.RunAsync
).
- User Input: The application prompts the user to enter a request (e.g., "print numbers from 1 to 5" or "read a file named 'test.txt' and print its content").
- Prompt Engineering: The user's input is embedded into a specific instruction for the Gemini AI:
"write a C# {userInput} as a simple script without namespaces, classes, or Main method, just the code to run with no explnations or anything, just the code."
- API Request: An HTTP POST request containing this structured prompt is sent to the Google Generative Language API endpoint for the
gemini-2.0-flash
model. - AI Response: The Gemini AI processes the request and returns a JSON response containing the generated C# code snippet.
- Code Extraction: The application parses this JSON response to extract the raw C# code. It also cleans up common markdown code block delimiters (e.g.,
```csharp
and```
). - Script Execution: The extracted C# code string is then executed using
CSharpScript.RunAsync
. TheSystem
namespace is automatically imported for the script's context. - Output (if any): If the generated script produces any console output (e.g., via
Console.WriteLine()
), it will be displayed in the terminal.
- .NET SDK (compatible with C# 10+ features like global using directives, though not explicitly used here, modern SDKs are recommended. For example, .NET 6 or later).
- A Google Gemini API Key. You can obtain one from Google AI Studio.
-
Clone the repository (or download the source files).
-
Set up the API Key:
- Open the
AIService.cs
file. - Locate the line:
private readonly string _key = "GEMINI_API_KEY";
- Replace
"GEMINI_API_KEY"
with your actual Google Gemini API key.
// In AIService.cs private readonly string _key = "YOUR_ACTUAL_GEMINI_API_KEY";
⚠️ Important Security Note: Hardcoding API keys directly into source code is generally not recommended for production applications. Consider using environment variables, configuration files (likeappsettings.json
), or secret management services for better security in real-world scenarios. - Open the
-
Navigate to the project directory in your terminal.
-
Build and run the project using the .NET CLI:
dotnet run
-
The application will start, and you'll see a prompt. Enter your request for the C# code you want the AI to generate and execute.
Example:
> write a script that prints "Hello from AI!" [+]Sending request... [+]Got the response! Hello from AI!
Another example:
> write a script that calculates 15 * 3 and prints the result [+]Sending request... [+]Got the response! 45
AIService.cs
:- Handles all communication with the Google Gemini API.
- Constructs the API request, including the endpoint, API key, and JSON payload.
- Sends the request and retrieves the response.
Program.cs
:- Contains the main application logic.
Main
method: Orchestrates reading user input, callingAIService
to get AI-generated code, extracting the code from the JSON response, and executing it usingCSharpScript.RunAsync
.ExtractText
method: Parses the JSON response from the AI and cleans the extracted code string.
The project relies on the following .NET libraries:
System.Net.Http
: For making HTTP requests to the Gemini API (implicitly part of the .NET SDK).System.Text.Json
: For parsing the JSON response from the API.Microsoft.CodeAnalysis.CSharp.Scripting
: For dynamically executing C# code snippets. You might need to add this package to your project if it's not already included:dotnet add package Microsoft.CodeAnalysis.CSharp.Scripting
- Security Risk: Executing code generated by an AI, especially from external sources or based on broad user inputs, carries significant security risks. The generated code could potentially perform malicious actions. Use this tool responsibly and be aware of the commands you are asking the AI to generate and execute. This project is intended as a demonstration and learning tool.
- API Usage & Costs: Be mindful of the usage limits and potential costs associated with the Google Gemini API.
- AI Reliability: The AI may not always generate correct, optimal, or safe code. The quality of the generated code depends heavily on the prompt and the AI's capabilities.