tRPC-Agent-Go provides complete integration with the Dify platform through the DifyAgent component. Developers can easily invoke Dify workflows and chatflows, seamlessly integrating Dify's powerful AI capabilities into tRPC-Agent-Go applications.
What is Dify?
Dify is an open-source LLM application development platform that provides visual AI workflow orchestration, prompt engineering, RAG (Retrieval-Augmented Generation), and other enterprise-grade features. With Dify, you can quickly build and deploy complex AI applications.
Core Capabilities
Unified Interface: Use Dify services like regular Agents without understanding Dify API details
Protocol Conversion: Automatically handle conversion between tRPC-Agent-Go message formats and Dify API
Streaming Support: Support both streaming and non-streaming response modes for real-time interaction
State Transfer: Support transferring session state to Dify workflows
Custom Extensions: Support custom request and response converters
DifyAgent: Calling Dify Services
Concept Introduction
DifyAgent is a special Agent implementation provided by tRPC-Agent-Go that forwards requests to Dify platform workflows or chatflow services. From the user's perspective, DifyAgent looks like a regular Agent, but it's actually a local proxy for Dify services.
Simple Understanding:
- I have a Dify workflow/chatflow → Call it in tRPC-Agent-Go through DifyAgent
- Use Dify's AI capabilities like a local Agent
Core Features
Transparent Proxy: Use Dify services like local Agents
Automatic Protocol Conversion: Automatically handle message format conversion with Dify API
Streaming Support: Support both streaming and non-streaming communication modes
State Transfer: Support transferring session state to Dify workflows
Custom Processing: Support custom streaming response handlers
Flexible Configuration: Support custom Dify client configuration
Use Cases
Enterprise AI Applications: Call internally deployed Dify services
Workflow Orchestration: Use Dify's visual workflow capabilities for complex business logic
RAG Applications: Build intelligent Q&A systems using Dify's knowledge base and RAG capabilities
Multi-Model Integration: Manage and call multiple LLM models uniformly through Dify
Quick Start
Prerequisites
Get Dify Service Information:
Dify service URL (e.g., https://api.dify.ai/v1)
API Secret (obtained from Dify application settings)
packagemainimport("context""fmt""log""time""github.com/cloudernative/dify-sdk-go""trpc.group/trpc-go/trpc-agent-go/agent""trpc.group/trpc-go/trpc-agent-go/agent/difyagent""trpc.group/trpc-go/trpc-agent-go/model""trpc.group/trpc-go/trpc-agent-go/runner""trpc.group/trpc-go/trpc-agent-go/session/inmemory")funcmain(){// Custom streaming response handlerstreamingHandler:=func(resp*model.Response)(string,error){iflen(resp.Choices)>0{content:=resp.Choices[0].Delta.Contentifcontent!=""{fmt.Print(content)// Real-time printing}returncontent,nil}return"",nil}// Create DifyAgent with streaming supportdifyAgent,err:=difyagent.New(difyagent.WithBaseUrl("https://api.dify.ai/v1"),difyagent.WithName("dify-streaming-assistant"),difyagent.WithDescription("Dify streaming assistant"),difyagent.WithEnableStreaming(true),// Enable streamingdifyagent.WithStreamingRespHandler(streamingHandler),difyagent.WithStreamingChannelBufSize(2048),// Streaming buffer sizedifyagent.WithGetDifyClientFunc(func(invocation*agent.Invocation)(*dify.Client,error){returndify.NewClientWithConfig(&dify.ClientConfig{Host:"https://api.dify.ai/v1",DefaultAPISecret:"your-api-secret",Timeout:60*time.Second,}),nil}),)iferr!=nil{log.Fatal(err)}// Create session service and RunnersessionService:=inmemory.NewSessionService()chatRunner:=runner.NewRunner("dify-streaming-runner",difyAgent,runner.WithSessionService(sessionService),)// Send messagefmt.Print("🤖 Assistant: ")events,err:=chatRunner.Run(context.Background(),"user-1","session-1",model.NewUserMessage("Please write a short story about a robot learning to paint"),)iferr!=nil{log.Fatal(err)}// Process streaming responseforevent:=rangeevents{ifevent.Error!=nil{log.Printf("Error: %s",event.Error.Message)}// streamingHandler will automatically handle and print content}fmt.Println()// New line}
difyAgent,_:=difyagent.New(difyagent.WithName("stateful-agent"),// Specify state keys to transferdifyagent.WithTransferStateKey("user_profile","conversation_context"),// ... other configs)// Set state in Runnerrunner.Run(ctx,userID,sessionID,model.NewUserMessage("Check my orders"),// These states will be transferred to Difyrunner.WithRuntimeState(map[string]interface{}{"user_profile":map[string]string{"name":"John","vip_level":"gold",},"conversation_context":"Discussing order issues",}),)
typeMyRequestConverterstruct{}func(c*MyRequestConverter)ConvertToDifyRequest(ctxcontext.Context,invocation*agent.Invocation,isStreambool,)(*dify.ChatMessageRequest,error){// Custom request building logicreq:=&dify.ChatMessageRequest{Query:extractQuery(invocation),ResponseMode:getResponseMode(isStream),ConversationID:getConversationID(invocation),User:invocation.RunOptions.UserID,Inputs:customInputs(invocation),}returnreq,nil}difyAgent,_:=difyagent.New(difyagent.WithCustomRequestConverter(&MyRequestConverter{}),// ... other configs)
import"os"difyAgent,_:=difyagent.New(difyagent.WithGetDifyClientFunc(func(invocation*agent.Invocation)(*dify.Client,error){returndify.NewClientWithConfig(&dify.ClientConfig{Host:os.Getenv("DIFY_BASE_URL"),DefaultAPISecret:os.Getenv("DIFY_API_SECRET"),Timeout:30*time.Second,}),nil}),// ... other configs)
// Use unique session ID for each user conversationsessionID:=fmt.Sprintf("user-%s-conv-%d",userID,time.Now().Unix())// Or use persistent session ID for long-term conversationssessionID:=getUserSessionID(userID)
Example Code
Complete examples are located in the project's examples/dify/ directory:
Q: What's the difference between DifyAgent and A2AAgent?
A:
- DifyAgent: Specifically for calling Dify platform services using Dify API
- A2AAgent: For calling remote Agent services that comply with A2A protocol
- Choice depends on backend service type
Q: How to use self-hosted Dify in enterprise intranet?
A: Simply set WithBaseUrl() to the intranet Dify service address, e.g.:
Q: How to choose between streaming and non-streaming modes?
A:
- Streaming: Suitable for long text generation, scenarios requiring real-time feedback
- Non-streaming: Suitable for short responses, batch processing scenarios
Q: How to debug Dify requests?
A: Implement a custom request converter with logging: