npc-clients-unity/Documentation/README.md

6.2 KiB

GumYum NPC SDK for Unity

Welcome to the GumYum NPC SDK for Unity! This SDK allows you to integrate AI-powered NPCs with deterministic spawning and dynamic dialogue into your Unity games.

Features

  • API Key Authentication: Simple setup with API keys from the GumYum dashboard
  • Deterministic NPC Spawning: Spawn the same NPCs with the same seed
  • Filtered Spawning: Spawn NPCs based on profession, location, personality type, and more
  • OpenAI-Compatible Chat: Use familiar chat completion APIs
  • Mood System: NPCs have dynamic moods that change based on conversations
  • Streaming Support: Real-time streaming of NPC responses
  • Unity Coroutine Support: Seamless integration with Unity's async patterns
  • Conversation History: Maintain context across multiple interactions

Quick Start

1. Installation

  1. Import the GumYum NPC package from the Unity Asset Store
  2. The package will be installed in Assets/GumYumNPC/

2. Get API Credentials

  1. Sign up at https://npc.gumyum.com
  2. Navigate to your dashboard
  3. Create a new API key pair
  4. Copy your public and secret keys

3. Basic Setup

Add the GumYumUnityClient to your scene:

using GumYum.NPC.Unity;

public class GameManager : MonoBehaviour
{
    private GumYumUnityClient client;
    
    void Start()
    {
        // Get the singleton instance
        client = GumYumUnityClient.Instance;
        
        // Set your API credentials
        client.SetCredentials("your-public-key", "your-secret-key");
        
        // Start spawning NPCs!
        StartCoroutine(SpawnMyFirstNPC());
    }
    
    IEnumerator SpawnMyFirstNPC()
    {
        // Spawn a random NPC from the "blade-runner" universe
        yield return client.SpawnNPCCoroutine("blade-runner", 42, null, npc =>
        {
            if (npc != null)
            {
                Debug.Log($"Spawned {npc.Name} the {npc.Profession}!");
            }
        });
    }
}

4. Chat with NPCs

IEnumerator ChatWithNPC(NPC npc, string message)
{
    yield return client.SimpleChatCoroutine(npc, message, response =>
    {
        if (response != null)
        {
            Debug.Log($"{npc.Name}: {response}");
        }
    });
}

Examples

The SDK includes several example scenes in the Samples~ folder:

  1. Basic Chat: Simple NPC spawning and chat interface
  2. Advanced Features: Filtered spawning, mood transitions, and streaming

To import samples:

  1. Open Package Manager (Window > Package Manager)
  2. Find GumYum NPC SDK
  3. Click on "Samples" and import the examples you want

Advanced Usage

Filtered NPC Spawning

// Spawn a female warrior or knight from the barracks
var filters = new Dictionary<string, object>
{
    ["profession"] = new[] { "warrior", "knight" },
    ["location"] = new[] { "barracks" },
    ["sex"] = new[] { "female" }
};

yield return client.SpawnFilteredNPCCoroutine("kingdom", 12345, filters, npc =>
{
    if (npc != null)
    {
        Debug.Log($"Spawned filtered NPC: {npc.GetInfo()}");
    }
});

Mood Transitions

NPCs have dynamic moods that change based on conversations:

// Check mood before conversation
string previousMood = npc.GetMood();

// Have a conversation...
yield return ChatWithNPC(npc, "I have terrible news!");

// Check if mood changed
if (npc.HasMoodChanged())
{
    Debug.Log($"Mood changed from {npc.GetPreviousMood()} to {npc.GetMood()}");
    Debug.Log($"Reason: {npc.GetLastMoodChangeReason()}");
}

Streaming Responses

For real-time chat experiences:

var messages = new List<ChatMessage>
{
    new ChatMessage { Role = "user", Content = "Tell me a story" }
};

// Enable streaming in the chat call
yield return client.ChatCoroutine(npc, messages, response =>
{
    // Final response received
}, temperature: 0.8, maxTokens: 2000);

// Listen to streaming events
npc.DialogueChunkReceived += (sender, chunk) =>
{
    // Update UI with each chunk as it arrives
    chatText.text += chunk;
};

Async/Await Support

The SDK also supports modern C# async patterns:

async Task SpawnAndChatAsync()
{
    var npc = await client.NPCs.SpawnAsync("blade-runner", 42);
    
    var messages = new List<ChatMessage>
    {
        new ChatMessage { Role = "user", Content = "Hello!" }
    };
    
    var response = await npc.Chat.CompletionsAsync(messages);
    Debug.Log(response.Choices[0].Message.Content);
}

API Reference

GumYumUnityClient

  • SetCredentials(apiKey, apiSecret): Set API credentials
  • SpawnNPCCoroutine(universeId, seed, npcId, callback): Spawn an NPC
  • SpawnFilteredNPCCoroutine(universeId, seed, filters, callback): Spawn filtered NPC
  • ChatCoroutine(npc, messages, callback, temperature, maxTokens): Chat with NPC
  • SimpleChatCoroutine(npc, message, callback, temperature, maxTokens): Simple chat helper

NPC Class

  • Name, Profession, PersonalityType: NPC properties
  • GetMood(), GetStressLevel(): Current state
  • Chat.CompletionsAsync(messages): Chat with the NPC
  • ChatWithHistoryAsync(message): Chat with conversation history
  • SaveToServerAsync(customName): Save NPC for later retrieval

Best Practices

  1. Singleton Usage: Use GumYumUnityClient.Instance for a single client across your game
  2. Error Handling: Always check if NPCs are null after spawning
  3. API Keys: Never commit API keys to source control. Use environment variables or Unity's secret management
  4. Coroutines: Use coroutines for better Unity integration, especially for UI updates
  5. Mood Awareness: Design conversations considering NPC mood states

Troubleshooting

NPCs not spawning

  • Check your API credentials are correct
  • Ensure you have an active internet connection
  • Check the Unity console for error messages

Mood not changing

  • Not all messages trigger mood changes
  • Mood transitions depend on NPC personality and context
  • Check HasMoodChanged() after conversations

Performance issues

  • Use appropriate max_tokens limits
  • Consider implementing response caching
  • Use streaming for long responses

Support

License

This SDK is licensed under the MIT License. See LICENSE file for details.