A Unity package that provides seamless integration with Dify, an open-source platform for building AI applications. This client enables Unity developers to easily incorporate AI-powered chat completion, audio-to-text conversion, and other AI services into their Unity projects.
- Chat Completion: Send messages to Dify AI applications with both blocking and streaming modes
- Audio-to-Text: Convert audio recordings to text using Dify's speech recognition
- Microphone Recording: Built-in microphone recording and playback functionality
- Visual Scripting Support: No-code integration with Unity Visual Scripting nodes
- File Upload: Support for uploading files to Dify applications
- Conversation Management: Handle multiple conversations and message history
- Unity Events: Native Unity event system integration for reactive programming
- Streaming Responses: Real-time streaming of AI responses with event callbacks
- Unity: 2022.1 or later
- Dependencies:
- Newtonsoft JSON (com.unity.nuget.newtonsoft-json 3.2.1)
- Platform: All Unity-supported platforms
- Open Unity Package Manager (
Window > Package Manager
) - Click the
+
button and selectAdd package from git URL...
- Enter the repository URL:
https://github.com/styly-dev/Dify-Unity-Client.git?path=Packages/com.from2001.dify-client
- Click
Add
- Download or clone this repository
- Copy the
Packages/com.from2001.dify-client
folder to your Unity project'sPackages
folder - Unity will automatically detect and import the package
Add the DifyManager
component to a GameObject in your scene:
// Get or add DifyManager component
DifyManager difyManager = gameObject.GetComponent<DifyManager>();
if (difyManager == null)
difyManager = gameObject.AddComponent<DifyManager>();
// Configure Dify settings
difyManager.DifyApiURL = "https://your-dify-instance.com/v1";
difyManager.DifyApiKey = "app-your-api-key-here";
difyManager.DifyUserId = "your-user-id";
// Send a blocking chat message
string response = await difyManager.SendChatMessage_blocking("Hello, how are you?");
Debug.Log("AI Response: " + response);
// Send a streaming chat message with events
difyManager.OnDifyMessage.AddListener(OnMessageReceived);
difyManager.SendChatMessage_Streaming("Tell me a story");
private void OnMessageReceived(string message)
{
Debug.Log("Received: " + message);
}
// Record audio and convert to text
difyManager.StartMicrophone();
// ... wait for user input ...
AudioClip recording = difyManager.StopMicrophone();
string transcription = await difyManager.AudioToText(recording);
Debug.Log("Transcription: " + transcription);
This package includes Visual Scripting nodes for no-code development:
- Start Microphone: Begin microphone recording
- Stop Microphone: Stop recording and get AudioClip
- Audio to Text: Convert AudioClip to text using Dify
- Send Chat Message (Streaming): Send messages with real-time streaming responses
- Open Visual Scripting graph editor
- Add nodes from the
Dify
category - Connect DifyManager reference (auto-finds if not specified)
- Wire up your logic flow
Property | Description | Example |
---|---|---|
DifyApiURL |
Your Dify instance API endpoint | "https://api.dify.ai/v1" |
DifyApiKey |
Application API key from Dify | "app-abc123..." |
DifyUserId |
Unique identifier for the user | "user-12345" |
The DifyManager provides several Unity Events for reactive programming:
OnDifyMessage
: Fired when a complete message is receivedOnDifyMessageChunk
: Fired for each chunk in streaming modeEvent_message
: Raw message events from DifyEvent_message_end
: Message completion eventsEvent_error
: Error events from Dify API
// Blocking chat message
Task<string> SendChatMessage_blocking(string query, Texture2D image = null)
// Streaming chat message
void SendChatMessage_Streaming(string query, Texture2D image = null)
// Stop streaming
void ChatMessage_streaming_stop()
// Microphone control
void StartMicrophone()
AudioClip StopMicrophone()
// Audio processing
Task<string> AudioToText(AudioClip audioClip)
void PlayAudioClip(AudioClip audioClip)
// Get conversation list
Task<ConversationsResponse> GetConversationsList(int limit = 20, string lastId = "")
// Get conversation messages
Task<ConversationMessagesResponse> GetConversationMessages(string conversationId, int limit = 20, string lastId = "")
// Rename conversation
Task<ConversationResponse> RenameConversation(string conversationId, bool autoGenerateName, string name = "")
The low-level API client provides direct access to Dify services:
// File upload
Task<FileUploadResponse> UploadFile(byte[] fileData, string fileName, string user)
// Raw API calls
Task<ChatCompletionResponse> ChatCompletion(string query, string user, bool streaming, string conversationId, Dictionary<string, object> inputs, List<FileInfo> files)
public class ChatExample : MonoBehaviour
{
public DifyManager difyManager;
public UnityEngine.UI.InputField inputField;
public UnityEngine.UI.Text responseText;
void Start()
{
// Configure Dify
difyManager.DifyApiURL = "https://your-dify-instance.com/v1";
difyManager.DifyApiKey = "your-api-key";
difyManager.DifyUserId = "user-example";
// Setup events
difyManager.OnDifyMessage.AddListener(OnMessageReceived);
}
public async void SendMessage()
{
string userMessage = inputField.text;
inputField.text = "";
responseText.text = "Thinking...";
try
{
string response = await difyManager.SendChatMessage_blocking(userMessage);
responseText.text = response;
}
catch (Exception e)
{
responseText.text = "Error: " + e.Message;
}
}
private void OnMessageReceived(string message)
{
responseText.text = message;
}
}
public class VoiceInputExample : MonoBehaviour
{
public DifyManager difyManager;
public UnityEngine.UI.Button recordButton;
public UnityEngine.UI.Text statusText;
private bool isRecording = false;
public void ToggleRecording()
{
if (!isRecording)
{
StartRecording();
}
else
{
StopRecording();
}
}
private void StartRecording()
{
difyManager.StartMicrophone();
isRecording = true;
statusText.text = "Recording...";
recordButton.GetComponentInChildren<UnityEngine.UI.Text>().text = "Stop";
}
private async void StopRecording()
{
AudioClip recording = difyManager.StopMicrophone();
isRecording = false;
statusText.text = "Processing...";
recordButton.GetComponentInChildren<UnityEngine.UI.Text>().text = "Record";
try
{
string transcription = await difyManager.AudioToText(recording);
statusText.text = "Transcription: " + transcription;
// Send transcription as chat message
string response = await difyManager.SendChatMessage_blocking(transcription);
statusText.text = "AI: " + response;
}
catch (Exception e)
{
statusText.text = "Error: " + e.Message;
}
}
}
Error: "Request failed: Unauthorized"
- Check that your API key is correct
- Ensure the API key has the necessary permissions
- Verify the Dify API URL is correct
Error: "DifyManager not found in the scene"
- Make sure you have a DifyManager component in your scene
- The Visual Scripting nodes will auto-find DifyManager if not explicitly connected
Audio recording not working
- Check microphone permissions on your target platform
- Ensure your device has a microphone available
- Verify Unity's microphone settings
- Enable debug logging in Unity Console
- Check Dify instance logs for API errors
- Verify network connectivity to your Dify instance
- Use Unity Profiler to monitor performance
We welcome contributions! Please see our contributing guidelines for details.
- Clone the repository
- Open in Unity 2022.1 or later
- Install required dependencies
- Run tests to verify setup
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Submit a pull request
This project is licensed under the MIT License - see the LICENSE file for details.
- Developer: STYLY, Inc.
- Repository: styly-dev/Dify-Unity-Client
- Dify Platform: dify.ai
- Issues: GitHub Issues
- Email: info@styly.inc
- Documentation: Unity Package Documentation
For more information about Dify, visit dify.ai or check out the Dify documentation.