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.
| Property | Type | Description |
|---|---|---|
IsInitialized | bool | Whether the system is initialized. |
IsAvailable | bool | Whether any cloud API key is configured. |
| Method | Signature | Description |
|---|---|---|
Initialize | static void Initialize() | Initialize the system. Called automatically. |
Shutdown | static void Shutdown() | Shutdown and cleanup. |
CraftCoreSettings
namespace CraftCore
[Serializable]
public class CraftCoreSettings
Singleton storing API keys, default provider, and model selections. Persisted in PlayerPrefs.
| Property | Type | Description |
|---|---|---|
Instance | CraftCoreSettings | Static. Singleton instance. Auto-loads from PlayerPrefs. |
DefaultApiProvider | ApiProvider | The default AI provider. |
Methods -- API Keys
| Method | Signature | Description |
|---|---|---|
GetApiKey | string GetApiKey(ApiProvider provider) | Get the decrypted API key. |
SetApiKey | void SetApiKey(ApiProvider provider, string apiKey) | Set and encrypt an API key. Auto-saves. |
RemoveApiKey | void RemoveApiKey(ApiProvider provider) | Remove an API key. |
HasApiKey | bool HasApiKey(ApiProvider provider) | Check if a key is configured. |
GetApiKeyPreview | string GetApiKeyPreview(ApiProvider provider) | Get masked preview (e.g., sk-a...x1z2). |
GetConfiguredProviders | List<ApiProvider> GetConfiguredProviders() | All providers with keys. |
GetConfiguredApiCount | int GetConfiguredApiCount() | Number of configured providers. |
Methods -- Models
| Method | Signature | Description |
|---|---|---|
GetSelectedModel | string GetSelectedModel(ApiProvider provider) | Get the selected model ID for a provider. |
SetSelectedModel | void SetSelectedModel(ApiProvider provider, string modelId) | Set the selected model. Auto-saves. |
Methods -- Lifecycle
| Method | Signature | Description |
|---|---|---|
Save | void Save() | Persist to PlayerPrefs. |
Reset | void 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
| Property | Type | Description |
|---|---|---|
Provider | ApiProvider | Which provider this client connects to. |
IsConfigured | bool | Whether the API key is set. |
AvailableModels | IReadOnlyList<ApiModelInfo> | Hardcoded model list for this provider. |
Methods
| Method | Signature | Description |
|---|---|---|
GenerateAsync | Task<ApiResponse> GenerateAsync(string prompt, ApiRequestOptions options, CancellationToken ct) | Single-prompt completion. |
GenerateStreamAsync | IAsyncEnumerable<string> GenerateStreamAsync(string prompt, ApiRequestOptions options, CancellationToken ct) | Streaming single-prompt completion. |
ChatAsync | Task<ApiResponse> ChatAsync(List<ChatMessage> messages, ApiRequestOptions options, CancellationToken ct) | Chat completion (most common). |
ChatStreamAsync | IAsyncEnumerable<string> ChatStreamAsync(List<ChatMessage> messages, ApiRequestOptions options, CancellationToken ct) | Streaming chat completion. |
ValidateApiKeyAsync | Task<bool> ValidateApiKeyAsync(CancellationToken ct) | Validate the API key with the provider. |
ListModelsAsync | Task<List<ApiModelInfo>> ListModelsAsync(CancellationToken ct) | Fetch available models from the provider API. |
ApiClientFactory
namespace CraftCore.Api
public static class ApiClientFactory
Creates IApiClient instances.
| Method | Signature | Description |
|---|---|---|
Create | static IApiClient Create(ApiProvider provider, string apiKey = null, string customEndpoint = null) | Create a client. Uses key from settings if not provided. |
CreateDefault | static IApiClient CreateDefault() | Create a client for the default provider. |
CreateForProduct | static 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
| Property | Type | Description |
|---|---|---|
Role | string | Message role: "system", "user", or "assistant". |
Content | string | Message content. |
| Factory Method | Description |
|---|---|
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
| Property | Type | Default | Description |
|---|---|---|---|
Model | string | null | Model ID (e.g., "gpt-4.1-mini"). Uses provider default if null. |
MaxTokens | int? | null | Maximum tokens in the response. |
Temperature | float? | null | Randomness (0.0 = deterministic, 1.0 = creative). |
TopP | float? | null | Nucleus sampling threshold. |
FrequencyPenalty | float? | null | Penalize repeated tokens. |
PresencePenalty | float? | null | Penalize tokens already present. |
StopSequences | List<string> | null | Sequences that stop generation. |
SystemPrompt | string | null | System prompt (alternative to ChatMessage.System). |
ResponseFormat | string | null | null, "json_object", or "json_schema". |
JsonSchema | string | null | JSON schema for structured output. |
JsonSchemaName | string | null | Name for the JSON schema. |
ApiResponse
namespace CraftCore.Api
public class ApiResponse
| Property | Type | Description |
|---|---|---|
Success | bool | Whether the call succeeded. |
Content | string | The AI's response text. |
Error | string | Error message if failed. |
PromptTokens | int | Tokens used by the prompt. |
CompletionTokens | int | Tokens used by the response. |
TotalTokens | int | Total tokens consumed. |
Model | string | Model that generated the response. |
FinishReason | string | Why generation stopped (e.g., "stop", "length"). |
ApiModelInfo
namespace CraftCore.Api
public class ApiModelInfo
| Property | Type | Description |
|---|---|---|
Id | string | Model identifier (e.g., "gpt-4.1-mini"). |
Name | string | Display name. |
Description | string | Short description. |
MaxTokens | int | Maximum context/output tokens. |
SupportsStreaming | bool | Whether streaming is available. |
SupportsVision | bool | Whether image input is supported. |
PricePerInputToken | float | Cost per input token (USD per 1M tokens). |
PricePerOutputToken | float | Cost 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.
| Property | Type | Description |
|---|---|---|
Instance | ApiUsageTracker | Static. Singleton. |
TotalInputTokens | long | Total input tokens used. |
TotalOutputTokens | long | Total output tokens used. |
TotalRequests | int | Total API requests made. |
TotalEstimatedCost | float | Estimated total cost in USD. |
| Event | Type | Description |
|---|---|---|
OnUsageUpdated | Action | Static. Fired when usage is recorded. |
CraftCoreProduct
namespace CraftCore
[Serializable]
public class CraftCoreProduct
Represents a CraftWorks product that uses CraftCore.
| Property | Type | Description |
|---|---|---|
Id | string | Unique product ID (e.g., "dialoguecraft"). |
Name | string | Display name. |
Version | string | Product version. |
Description | string | Short description. |
Icon | string | Emoji icon. |
AccentColor | string | Hex color (e.g., "#F5A623"). |
PackageName | string | Unity package name. |
SupportedApiProviders | List<ApiProvider> | Supported providers. |
| Method | Signature | Description |
|---|---|---|
GetInferenceConfig | ProductInferenceConfig GetInferenceConfig() | Get per-product AI config. |
SetInferenceConfig | void SetInferenceConfig(ProductInferenceConfig config) | Set and save per-product config. |
ResetInferenceConfig | void ResetInferenceConfig() | Reset to auto (global default). |
CraftCoreProductRegistry
namespace CraftCore
public static class CraftCoreProductRegistry
| Method | Signature | Description |
|---|---|---|
Register | static void Register(CraftCoreProduct product) | Register a product. |
Unregister | static void Unregister(string productId) | Unregister a product. |
GetProduct | static CraftCoreProduct GetProduct(string productId) | Get a product by ID. |
GetRegisteredProducts | static List<CraftCoreProduct> GetRegisteredProducts() | Get all registered products. |
IsRegistered | static bool IsRegistered(string productId) | Check if a product is registered. |
GetProductConfig | static ProductInferenceConfig GetProductConfig(string productId) | Get a product's inference config. |
GetAllSupportedApiProviders | static HashSet<ApiProvider> GetAllSupportedApiProviders() | Providers used by any product. |
GetProductsForApiProvider | static 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).
| Property | Type | Description |
|---|---|---|
IsAuto | bool | True when using the global default provider. |
ApiProvider | ApiProvider | Resolved provider (auto resolves to global default). |
RawProvider | int | Raw value including Auto (-1). |
CustomEndpoint | string | Custom endpoint URL. |
ApiModel | string | Model override. |
| Method | Signature | Description |
|---|---|---|
SetAuto | void 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;
}
}