Skip to main content

CraftCore API Reference

All classes are in the CraftCore or CraftCore.Api namespace.


CraftCoreAI

namespace CraftCore
public static class CraftCoreAI

Main entry point for the CraftCore system.

PropertyTypeDescription
IsInitializedboolWhether the system is initialized.
IsAvailableboolWhether any cloud API key is configured.
MethodSignatureDescription
Initializestatic void Initialize()Initialize the system. Called automatically.
Shutdownstatic void Shutdown()Shutdown and cleanup.

CraftCoreSettings

namespace CraftCore
[Serializable]
public class CraftCoreSettings

Singleton storing API keys, default provider, and model selections. Persisted in PlayerPrefs.

PropertyTypeDescription
InstanceCraftCoreSettingsStatic. Singleton instance. Auto-loads from PlayerPrefs.
DefaultApiProviderApiProviderThe default AI provider.

Methods -- API Keys

MethodSignatureDescription
GetApiKeystring GetApiKey(ApiProvider provider)Get the decrypted API key.
SetApiKeyvoid SetApiKey(ApiProvider provider, string apiKey)Set and encrypt an API key. Auto-saves.
RemoveApiKeyvoid RemoveApiKey(ApiProvider provider)Remove an API key.
HasApiKeybool HasApiKey(ApiProvider provider)Check if a key is configured.
GetApiKeyPreviewstring GetApiKeyPreview(ApiProvider provider)Get masked preview (e.g., sk-a...x1z2).
GetConfiguredProvidersList<ApiProvider> GetConfiguredProviders()All providers with keys.
GetConfiguredApiCountint GetConfiguredApiCount()Number of configured providers.

Methods -- Models

MethodSignatureDescription
GetSelectedModelstring GetSelectedModel(ApiProvider provider)Get the selected model ID for a provider.
SetSelectedModelvoid SetSelectedModel(ApiProvider provider, string modelId)Set the selected model. Auto-saves.

Methods -- Lifecycle

MethodSignatureDescription
Savevoid Save()Persist to PlayerPrefs.
Resetvoid Reset()Reset to defaults (keeps API keys).

IApiClient

namespace CraftCore.Api
public interface IApiClient

Interface for AI provider clients. Built-in implementations: OpenAIClient, AnthropicClient, GoogleAIClient.

Properties

PropertyTypeDescription
ProviderApiProviderWhich provider this client connects to.
IsConfiguredboolWhether the API key is set.
AvailableModelsIReadOnlyList<ApiModelInfo>Hardcoded model list for this provider.

Methods

MethodSignatureDescription
GenerateAsyncTask<ApiResponse> GenerateAsync(string prompt, ApiRequestOptions options, CancellationToken ct)Single-prompt completion.
GenerateStreamAsyncIAsyncEnumerable<string> GenerateStreamAsync(string prompt, ApiRequestOptions options, CancellationToken ct)Streaming single-prompt completion.
ChatAsyncTask<ApiResponse> ChatAsync(List<ChatMessage> messages, ApiRequestOptions options, CancellationToken ct)Chat completion (most common).
ChatStreamAsyncIAsyncEnumerable<string> ChatStreamAsync(List<ChatMessage> messages, ApiRequestOptions options, CancellationToken ct)Streaming chat completion.
ValidateApiKeyAsyncTask<bool> ValidateApiKeyAsync(CancellationToken ct)Validate the API key with the provider.
ListModelsAsyncTask<List<ApiModelInfo>> ListModelsAsync(CancellationToken ct)Fetch available models from the provider API.

ApiClientFactory

namespace CraftCore.Api
public static class ApiClientFactory

Creates IApiClient instances.

MethodSignatureDescription
Createstatic IApiClient Create(ApiProvider provider, string apiKey = null, string customEndpoint = null)Create a client. Uses key from settings if not provided.
CreateDefaultstatic IApiClient CreateDefault()Create a client for the default provider.
CreateForProductstatic IApiClient CreateForProduct(string productId)Create a client using a product's config.

Usage

// Default provider
var client = ApiClientFactory.CreateDefault();

// Specific provider
var client = ApiClientFactory.Create(ApiProvider.Anthropic);

// Custom endpoint
var client = ApiClientFactory.Create(ApiProvider.Custom, "your-key", "http://localhost:11434/v1");

// For a CraftWorks product
var client = ApiClientFactory.CreateForProduct("dialoguecraft");

ChatMessage

namespace CraftCore.Api
public class ChatMessage
PropertyTypeDescription
RolestringMessage role: "system", "user", or "assistant".
ContentstringMessage content.
Factory MethodDescription
ChatMessage.System(string content)Create a system message.
ChatMessage.User(string content)Create a user message.
ChatMessage.Assistant(string content)Create an assistant message.

ApiRequestOptions

namespace CraftCore.Api
public class ApiRequestOptions
PropertyTypeDefaultDescription
ModelstringnullModel ID (e.g., "gpt-4.1-mini"). Uses provider default if null.
MaxTokensint?nullMaximum tokens in the response.
Temperaturefloat?nullRandomness (0.0 = deterministic, 1.0 = creative).
TopPfloat?nullNucleus sampling threshold.
FrequencyPenaltyfloat?nullPenalize repeated tokens.
PresencePenaltyfloat?nullPenalize tokens already present.
StopSequencesList<string>nullSequences that stop generation.
SystemPromptstringnullSystem prompt (alternative to ChatMessage.System).
ResponseFormatstringnullnull, "json_object", or "json_schema".
JsonSchemastringnullJSON schema for structured output.
JsonSchemaNamestringnullName for the JSON schema.

ApiResponse

namespace CraftCore.Api
public class ApiResponse
PropertyTypeDescription
SuccessboolWhether the call succeeded.
ContentstringThe AI's response text.
ErrorstringError message if failed.
PromptTokensintTokens used by the prompt.
CompletionTokensintTokens used by the response.
TotalTokensintTotal tokens consumed.
ModelstringModel that generated the response.
FinishReasonstringWhy generation stopped (e.g., "stop", "length").

ApiModelInfo

namespace CraftCore.Api
public class ApiModelInfo
PropertyTypeDescription
IdstringModel identifier (e.g., "gpt-4.1-mini").
NamestringDisplay name.
DescriptionstringShort description.
MaxTokensintMaximum context/output tokens.
SupportsStreamingboolWhether streaming is available.
SupportsVisionboolWhether image input is supported.
PricePerInputTokenfloatCost per input token (USD per 1M tokens).
PricePerOutputTokenfloatCost per output token (USD per 1M tokens).

ApiProvider

namespace CraftCore
public enum ApiProvider
{
OpenAI, // OpenAI (GPT family)
Anthropic, // Anthropic (Claude family)
Google, // Google AI (Gemini family)
Custom // Custom OpenAI-compatible endpoint
}

ApiUsageTracker

namespace CraftCore
[Serializable]
public class ApiUsageTracker

Tracks API usage and estimated costs. Persisted in PlayerPrefs.

PropertyTypeDescription
InstanceApiUsageTrackerStatic. Singleton.
TotalInputTokenslongTotal input tokens used.
TotalOutputTokenslongTotal output tokens used.
TotalRequestsintTotal API requests made.
TotalEstimatedCostfloatEstimated total cost in USD.
EventTypeDescription
OnUsageUpdatedActionStatic. Fired when usage is recorded.

CraftCoreProduct

namespace CraftCore
[Serializable]
public class CraftCoreProduct

Represents a CraftWorks product that uses CraftCore.

PropertyTypeDescription
IdstringUnique product ID (e.g., "dialoguecraft").
NamestringDisplay name.
VersionstringProduct version.
DescriptionstringShort description.
IconstringEmoji icon.
AccentColorstringHex color (e.g., "#F5A623").
PackageNamestringUnity package name.
SupportedApiProvidersList<ApiProvider>Supported providers.
MethodSignatureDescription
GetInferenceConfigProductInferenceConfig GetInferenceConfig()Get per-product AI config.
SetInferenceConfigvoid SetInferenceConfig(ProductInferenceConfig config)Set and save per-product config.
ResetInferenceConfigvoid ResetInferenceConfig()Reset to auto (global default).

CraftCoreProductRegistry

namespace CraftCore
public static class CraftCoreProductRegistry
MethodSignatureDescription
Registerstatic void Register(CraftCoreProduct product)Register a product.
Unregisterstatic void Unregister(string productId)Unregister a product.
GetProductstatic CraftCoreProduct GetProduct(string productId)Get a product by ID.
GetRegisteredProductsstatic List<CraftCoreProduct> GetRegisteredProducts()Get all registered products.
IsRegisteredstatic bool IsRegistered(string productId)Check if a product is registered.
GetProductConfigstatic ProductInferenceConfig GetProductConfig(string productId)Get a product's inference config.
GetAllSupportedApiProvidersstatic HashSet<ApiProvider> GetAllSupportedApiProviders()Providers used by any product.
GetProductsForApiProviderstatic List<CraftCoreProduct> GetProductsForApiProvider(ApiProvider provider)Products using a specific provider.

ProductInferenceConfig

namespace CraftCore
[Serializable]
public class ProductInferenceConfig

Per-product AI configuration. Defaults to Auto (inherits global default).

PropertyTypeDescription
IsAutoboolTrue when using the global default provider.
ApiProviderApiProviderResolved provider (auto resolves to global default).
RawProviderintRaw value including Auto (-1).
CustomEndpointstringCustom endpoint URL.
ApiModelstringModel override.
MethodSignatureDescription
SetAutovoid SetAuto()Reset to auto mode.

Usage Example

using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using CraftCore;
using CraftCore.Api;

public static class MyAIHelper
{
public static async Task<string> AskAI(string question)
{
if (!CraftCoreAI.IsAvailable)
return null;

var client = ApiClientFactory.CreateDefault();

var messages = new List<ChatMessage>
{
ChatMessage.System("You are a helpful game design assistant."),
ChatMessage.User(question)
};

var options = new ApiRequestOptions
{
MaxTokens = 512,
Temperature = 0.7f
};

var response = await client.ChatAsync(messages, options);

if (response.Success)
return response.Content;

Debug.LogError($"AI call failed: {response.Error}");
return null;
}
}