AI DevKit
Glitch9 Inc.Glitch9 DocsDiscordIssues
  • Introduction
    • AI DevKit 3.0
    • Update Logs
    • Troubleshooting
      • ❗Issues After Updating AIDevKit?
      • ❗The type or namespace name 'Newtonsoft' could not be found
      • ❗Build Error: The name 'UnityMenu' does not exist in the current context
      • ❗Model 'modelName' not found
      • ❗The model `model name` does not exist or you do not have access to it
      • ❗The type or namespace name 'AndroidJavaObject' could not be found
      • ❗The type or namaspace name 'Plastic' does not exist
      • ❗Build Error: The name 'Asset Database' does not exist in the current context
      • ❗'ModelData.Create(Provider, string, UnixTime?, string)': not all code paths return a value
      • ⚠️ Timeout Issues
      • ⚠️ Receiving a “HTTP/1.1 400 Bad Request” Error?
    • FAQ
      • My OpenAI API free trial has ended or is inactive.
  • Quick Start
    • Get API Keys
      • OpenAI API Key Guide
      • Google API Key Guide
      • ElevenLabs API Key Guide
    • Text Generation
    • C# Object Generation
    • Image Generation
    • Sound Effect Generation
    • Text to Speech (TTS)
    • Speech to Text (STT)
    • Voice Changer
    • Audio Isolation
  • Pro Features
    • Generation Menu
      • Code Generators
        • C# Script Generator
        • Unity Component Generator
    • Editor Chat
    • Editor Vision (TTI, ITI)
    • Editor Speech (TTS)
    • Management Tools
      • Prompt History Viewer
      • AI Model Manager
      • TTS Voice Manager
      • OpenAI File Manager
      • OpenAI Assistant Manager
      • ElevenLabs Voice Library
  • Assistants API (OpenAI)
    • How it works
    • Creating custom functions
    • Creating assistants API
  • Advanced API Supports
    • OpenAI API
      • 💬Chat completions
      • 🖼️Image operations
      • 🗣️Text to speech
      • 🎙️Speech to text
        • Recording real-time in Unity
      • 💾Files
      • 🔎Embeddings
      • 🛡️Moderations
      • ⚙️Fine-tuning
    • Google API
      • 📝System instructions
      • 💬Text generation
      • ⚙️Fine-tuning
      • ▶️Fucntion calling
      • 🔎Embeddings
      • 🛡️Safety
      • 💻Code execution
    • ElevenLabs API
  • Legacy Documents
    • AI DevKit 1.0 - 2.0
      • AI DevKit 2.0
      • AI DevKit 1.0
      • Preperation
      • Event Handlers
      • Scriptable Toolkits
        • Chat Streamer
        • Image Generator
        • Voice Transcriber
        • Voice Generator
      • Editor Tools
Powered by GitBook
On this page
  1. Advanced API Supports
  2. Google API

Code execution

Enable code execution on the model

You can enable code execution on the model, as shown here:

using Glitch9.AIDevKit.Google.GenerativeAI;

var model = new GenerativeModel(
    GeminiModel.Gemini15Pro, 
    tools: "code_execution");

var response = await model.GenerateContentAsync(
    "What is the sum of the first 50 prime numbers? " +
    "Generate and run code for the calculation, and make sure you get all 50.");

Debug.Log(response.Text);
import os
import google.generativeai as genai

genai.configure(api_key=os.environ['API_KEY'])

model = genai.GenerativeModel(
    model_name='gemini-1.5-pro',
    tools='code_execution')

response = model.generate_content((
    'What is the sum of the first 50 prime numbers? '
    'Generate and run code for the calculation, and make sure you get all 50.'))

print(response.text)

The output might look something like this:

```csharp
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        int sumOfFirst50Primes = SumOfPrimes(50);
        Console.WriteLine($"The sum of the first 50 prime numbers is: {sumOfFirst50Primes}");
    }

    static bool IsPrime(int n)
    {
        if (n <= 1)
            return false;
        for (int i = 2; i <= Math.Sqrt(n); i++)
        {
            if (n % i == 0)
                return false;
        }
        return true;
    }

    static int SumOfPrimes(int n)
    {
        List<int> primes = new List<int>();
        int i = 2;
        while (primes.Count < n)
        {
            if (IsPrime(i))
                primes.Add(i);
            i++;
        }
        int sum = 0;
        foreach (int prime in primes)
        {
            sum += prime;
        }
        return sum;
    }
}
```

**Explanation:**

1. **`is_prime(n)` Function:**
   - Takes an integer `n` as input.
   - Returns `False` for numbers less than or equal to 1 (not prime).
   - Iterates from 2 up to the square root of `n`. If `n` is divisible by any
     number in this range, it's not prime, and we return `False`.
   - If the loop completes without finding a divisor, the number is prime, and
     we return `True`.

2. **`sum_of_primes(n)` Function:**
   - Takes an integer `n` (number of primes desired) as input.
   - Initializes an empty list `primes` to store the prime numbers.
   - Starts a loop, iterating through numbers starting from 2.
   - For each number `i`, it checks if it's prime using the `is_prime()` function.
   - If `i` is prime, it's appended to the `primes` list.
   - The loop continues until the `primes` list has `n` prime numbers.
   - Finally, it calculates and returns the sum of all the prime numbers in the
     `primes` list.

3. **Main Part:**
   - Calls `sum_of_primes(50)` to get the sum of the first 50 prime numbers.
   - Prints the result.

**Output:**

```
The sum of the first 50 prime numbers is: 5117
```

Enable code execution on the request

Alternatively, you can enable code execution on the call to generate_content:

using Glitch9.AIDevKit.Google.GenerativeAI;

GenerativeModel model = new(
    GeminiModel.Gemini15Pro);

var response = await model.GenerateContentAsync(
    "What is the sum of the first 50 prime numbers? " +
    "Generate and run code for the calculation, and make sure you get all 50.",
    tools: "code_execution");

Debug.Log(response.GetOutputText());
import os
import google.generativeai as genai

genai.configure(api_key=os.environ['API_KEY'])

model = genai.GenerativeModel(model_name='gemini-1.5-pro')

response = model.generate_content(
    ('What is the sum of the first 50 prime numbers? '
    'Generate and run code for the calculation, and make sure you get all 50.'),
    tools='code_execution')

print(response.text)

Use code execution in chat

You can also use code execution as part of a chat.

using Glitch9.AIDevKit.Google.GenerativeAI;

var model = new GenerativeModel(GeminiModel.Gemini15Pro);

var chat = model.StartChat();

var response = await chat.SendMessageAsync(
    "What is the sum of the first 50 prime numbers? " +
    "Generate and run code for the calculation, and make sure you get all 50.");

Debug.Log(response.Text);
import os
import google.generativeai as genai

genai.configure(api_key=os.environ['API_KEY'])

model = genai.GenerativeModel(model_name='gemini-1.5-pro')

chat = model.start_chat()

response = chat.send_message((
    'What is the sum of the first 50 prime numbers? '
    'Generate and run code for the calculation, and make sure you get all 50.'))

print(response.text)

Code execution versus function calling

  • Code execution lets the model run code in the API backend in a fixed, isolated environment.

  • Function calling lets you run the functions that the model requests, in whatever environment you want.

In general you should prefer to use code execution if it can handle your use case. Code execution is simpler to use (you just enable it) and resolves in a single GenerateContent request (thus incurring a single charge). Function calling takes an additional GenerateContent request to send back the output from each function call (thus incurring multiple charges).

For most cases, you should use function calling if you have your own functions that you want to run locally, and you should use code execution if you'd like the API to write and run Python code for you and return the result.

PreviousSafetyNextElevenLabs API

Last updated 10 months ago

Code execution and are similar features:

💻
function calling
LogoCode execution  |  Gemini API  |  Google for DevelopersGoogle for Developers
Google official document