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
  • Chat Operations Overview:
  • Sample Code for Chat Completions:
  1. Advanced API Supports
  2. OpenAI API

Chat completions

PreviousOpenAI APINextImage operations

Last updated 10 months ago

To incorporate OpenAI's conversational AI capabilities into your Unity project, you'll be utilizing a variety of requests centered around chat interactions through the OpenAI with unity asset. These requests enable the integration of OpenAI's sophisticated language models, like GPT-4, into your applications, facilitating dynamic and intelligent conversations. Whether you're aiming to develop engaging NPCs, automated customer service bots, or interactive storytelling experiences, the chat functionalities offered by OpenAI can significantly enhance the interactivity of your Unity projects.

For a deep dive into the technical details and options available for these requests, refer to the .

Chat Operations Overview:

  1. Chat Completion: Generate conversational responses based on input prompts. This is the core of creating dynamic dialogues where the AI provides contextually relevant answers or reactions to user inputs.

  2. Chat Streaming: For applications requiring real-time interaction, streaming chat completions allow your application to receive responses as they are generated. This approach is ideal for simulating live conversations, enhancing the responsiveness and dynamism of chatbots or virtual assistants.

Sample Code for Chat Completions:

1. Standard Chat Completion Request

This approach sends a prompt to OpenAI and receives a single, complete response. It's straightforward and suitable for most use cases where an immediate and full response is expected.

var request = new ChatCompletionRequest.Builder()
    .SetModel(GPTModel.GPT4_0125Preview) 
    .SetPrompt("Your prompt here")
    .SetMaxTokens(50) // Optional: Set the maximum number of tokens to generate.
    .Build();

ChatCompletion completion = await request.ExecuteAsync();

Debug.Log(completion.Choices[0].Message);
from openai import OpenAI
client = OpenAI()

completion = client.chat.completions.create(
  model="gpt-4o",
  messages=[
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "Hello!"}
  ]
)

print(completion.choices[0].message)

2. Streaming Chat Completion Request

For receiving responses as they're generated, use the streaming request. This method is beneficial when you want to process or display parts of the response as soon as they become available, especially for interactive applications.

var request = new ChatCompletionRequest.Builder()
    .SetModel(GPTModel.GPT4_0125Preview) 
    .SetPrompt("Your prompt here")
    .SetMaxTokens(50) // Optional: Set the maximum number of tokens to generate.
    .SetStream(true) // Enable streaming.
    .Build();

await request.StreamAsync(streamedResponse =>
{
    Debug.Log($"Streamed chunk: {streamedResponse}");
    // Handle each piece of the response as it arrives.
});

Or you can create a stream handler to handle the streamed response.

var streamHandler = new StreamHandler();

streamHandler.OnStart += sender =>
{
    Debug.Log("Stream started");
};

streamHandler.OnStream += (sender, message) =>
{
    Debug.Log($"Streamed chunk: {message}");
    // Handle each piece of the response as it arrives.
};

streamHandler.OnDone += sender =>
{
    Debug.Log("Stream done");
};

await request.StreamAsync(streamHandler);
💬
Chat API Reference