
Security News
Open VSX Begins Implementing Pre-Publish Security Checks After Repeated Supply Chain Incidents
Following multiple malicious extension incidents, Open VSX outlines new safeguards designed to catch risky uploads earlier.
trpc.group/trpc-go/trpc-agent-go/examples/dify
Advanced tools
This directory contains comprehensive examples demonstrating how to use the difyagent package to integrate with Dify workflows and chatflows.
Before running any examples, set up the required environment variables:
export DIFY_BASE_URL="https://api.dify.ai/v1" # or your self-hosted URL
export DIFY_API_SECRET="your-dify-api-secret"
basic_chat/)Purpose: Demonstrates simple non-streaming chat interaction with Dify.
Key Features:
Run:
cd basic_chat
go run main.go
Expected Output:
🤖 Starting Dify Chat Example
==================================================
👤 User: Hello! Can you introduce yourself?
🤖 Assistant: Hello! I'm an AI assistant powered by Dify...
👤 User: What can you help me with?
🤖 Assistant: I can help you with various tasks...
streaming_chat/)Purpose: Shows real-time streaming responses from Dify.
Key Features:
Run:
cd streaming_chat
go run main.go
Expected Output:
🚀 Starting Dify Streaming Chat Example
============================================================
👤 User: Please write a short story about a robot learning to paint
🤖 Assistant: Once upon a time, in a small workshop...
[content streams in real-time]
📊 Response Stats:
• Duration: 2.3s
• Chunks: 15
• Characters: 287
• Speed: 124.8 chars/sec
advanced_usage/)Purpose: Demonstrates advanced features like custom converters and state management.
Key Features:
Run:
cd advanced_usage
go run main.go
Expected Output:
🔧 Starting Dify Advanced Usage Example
============================================================
📋 Scenario 1: Expert user asking about quantum computing
👤 User: Explain quantum computing
⚙️ User Preferences:
• user_language: en
• response_tone: professional
• expertise_level: expert
• response_format: detailed
🤖 Assistant: [Dify:conv-123] Quantum computing is a revolutionary...
📊 Event Metadata:
• dify_conversation_id: conv-123
• dify_message_id: msg-456
• custom_processed: true
difyAgent, err := difyagent.New(
difyagent.WithBaseUrl("https://api.dify.ai/v1"),
difyagent.WithName("my-assistant"),
difyagent.WithDescription("My custom assistant"),
)
difyAgent, err := difyagent.New(
difyagent.WithBaseUrl(difyBaseURL),
difyagent.WithEnableStreaming(true),
difyagent.WithStreamingChannelBufSize(2048),
difyagent.WithStreamingRespHandler(customHandler),
)
The WithGetDifyClientFunc option allows you to customize the Dify client creation for each invocation. This is particularly useful when you need:
difyAgent, err := difyagent.New(
// Custom client function - called for each invocation
difyagent.WithGetDifyClientFunc(func(invocation *agent.Invocation) (*dify.Client, error) {
// Access invocation context for dynamic configuration
userID := invocation.Session.UserID
// Example: Use different API keys per user
apiSecret := getUserAPISecret(userID)
// Example: Custom timeout based on user tier
timeout := getUserTimeout(userID)
return dify.NewClientWithConfig(&dify.ClientConfig{
Host: baseURL, // Can be dynamic too
DefaultAPISecret: apiSecret, // Per-user API secret
Timeout: timeout, // Custom timeout
// Add custom headers if needed
// Headers: map[string]string{"X-User-ID": userID},
}), nil
}),
)
Note: If WithGetDifyClientFunc is not provided, the agent will create a default client using the base configuration.
Customize how Dify responses are converted to events:
type CustomEventConverter struct{}
func (c *CustomEventConverter) ConvertToEvent(
resp *dify.ChatMessageResponse,
agentName string,
invocation *agent.Invocation,
) *event.Event {
// Custom conversion logic
return event
}
Customize how invocations are converted to Dify requests:
type CustomRequestConverter struct{}
func (c *CustomRequestConverter) ConvertToDifyRequest(
ctx context.Context,
invocation *agent.Invocation,
isStream bool,
) (*dify.ChatMessageRequest, error) {
// Custom request building logic
return request, nil
}
Transfer session state to Dify inputs:
difyAgent, err := difyagent.New(
difyagent.WithTransferStateKey("user_language", "user_preferences"),
)
// Use with runtime state
events, err := runner.Run(
ctx, userID, sessionID,
model.NewUserMessage("Hello"),
agent.WithRuntimeState(map[string]any{
"user_language": "en",
"user_preferences": "detailed_responses",
}),
)
Missing API Secret:
DIFY_API_SECRET environment variable is required
Solution: Set the environment variable
Connection Timeout:
context deadline exceeded
Solution: Increase timeout or check network connectivity
Invalid API Secret:
401 Unauthorized
Solution: Verify your API secret is correct
events, err := runner.Run(ctx, userID, sessionID, message)
if err != nil {
log.Printf("Runner error: %v", err)
return
}
for event := range events {
if event.Error != nil {
log.Printf("Event error: %s", event.Error.Message)
continue
}
// Process successful event
}
// Use context with timeout
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
// Use consistent session IDs for conversation continuity
sessionID := fmt.Sprintf("user-%s-session-%d", userID, time.Now().Unix())
// Implement retry logic for transient errors
for attempts := 0; attempts < 3; attempts++ {
events, err := runner.Run(ctx, userID, sessionID, message)
if err == nil {
break
}
time.Sleep(time.Duration(attempts+1) * time.Second)
}
// Use appropriate buffer sizes for streaming
difyagent.WithStreamingChannelBufSize(2048)
// Handle streaming gracefully
streamingHandler := func(resp *model.Response) (string, error) {
if len(resp.Choices) > 0 {
content := resp.Choices[0].Delta.Content
// Process content immediately
fmt.Print(content)
return content, nil
}
return "", nil
}
Each example includes basic error handling and logging. For production use, consider:
Enable debug logging to see detailed request/response information:
// Add debug logging to your Dify client configuration
client := dify.NewClientWithConfig(&dify.ClientConfig{
Host: baseURL,
DefaultAPISecret: apiSecret,
Debug: true, // Enable debug mode
})
After running these examples:
For issues specific to:
FAQs
Unknown package
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
Following multiple malicious extension incidents, Open VSX outlines new safeguards designed to catch risky uploads earlier.

Research
/Security News
Threat actors compromised four oorzc Open VSX extensions with more than 22,000 downloads, pushing malicious versions that install a staged loader, evade Russian-locale systems, pull C2 from Solana memos, and steal macOS credentials and wallets.

Security News
Lodash 4.17.23 marks a security reset, with maintainers rebuilding governance and infrastructure to support long-term, sustainable maintenance.