dify

package module
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 17, 2024 License: MIT Imports: 6 Imported by: 0

README

dify-go

Go SDK for langgenius/dify.

Quick Start

Install the Dify Go package:

go get github.com/kervinchang/dify-go

Initialize a Dify client:

config := dify.ClientConfig{
	BaseURL: "https://your-dify-server-endpoint.com",
	APIKey: "your-api-key",
}
client, err := dify.NewClient(config)
if err != nil {
	log.Fatalf("failed to create Dify client: %v\n", err)
}

Send a request to the CreateChatMessage API:

request := dify.ChatMessageRequest{
	Inputs:        make(map[string]interface{}),
	query:         query,
	User:          "your-user-id",
}
response, err := client.CreateChatMessage(ctx, request)
if err != nil {
	log.Fatalf("failed to create chat message in blocking mode: %v\n", err)
}
log.Printf("response: %v\n", response) // dify.ChatCompletionResponse

Send a request to the CreateChatMessage API for streaming responses:

request := dify.ChatMessageRequest{
	Inputs:       make(map[string]interface{}),
	query:        query,
	User:         "your-user-id",
}
stream, err := client.CreateChatMessageStream(ctx, request)
if err != nil {
	log.Fatalf("failed to create chat message in streaming mode: %v\n", err)
}
for reponse := range stream {
	log.Printf("response: %v\n", response) // dify.ChunkChatCompletionResponse
}

Send a request to the CreateCompletionMessage API:

request := dify.CompletionMessageRequest{
	Inputs:       map[string]interface{}{"query": query}, 
	User:         "your-user-id",
}
response, err := client.CreateCompletionMessage(ctx, request)
if err != nil {
	log.Fatalf("failed to create completion message in blocking mode: %v\n", err)
}
log.Printf("response: %v\n", response) // dify.ChatCompletionResponse

Send a request to the CreateCompletionMessage API for streaming responses:

request := dify.CompletionMessageRequest{
	Inputs:       map[string]interface{}{"query": query},
	User:         "your-user-id",
}
stream, err := client.CreateCompletionMessageStream(ctx, request)
if err != nil {
	log.Fatalf("failed to create completion message in streaming mode: %v\n", err)
}
for response := range stream {
	log.Printf("response: %v\n", response) // dify.ChunkChatCompletionResponse
}

Send a requrest to the RunWorkflow API:

request := dify.RunWorkflowRequest{
	Inputs:       map[string]interface{}{}, 
	User:         "your-user-id",
}
response, err := client.RunWorkflow(ctx, request)
if err != nil {
	log.Fatalf("failed to run workflow in blocking mode: %v\n", err)
}
log.Printf("response: %v\n", response) // dify.CompletionResponse

Send a request to the RunWorkflow API for streaming responses:

request := dify.RunWorkflowRequest{
	Inputs:       map[string]interface{}{}, 
	User:         "your-user-id",
}
stream, err := client.RunWorkflowStream(ctx, request)
if err != nil {
	log.Fatalf("failed to run workflow in streaming mode: %v\n", err)
}
for response := range stream {
	log.Printf("response: %v\n", response) // dify.ChunkCompletionResponse
}

Documentation

Index

Constants

View Source
const CompletionMessageEndpoint = "/v1/completion-messages"

CompletionMessageEndpoint - Endpoint for creating a completion message.

View Source
const WorkflowEndpoint = "/v1/workflows"

WorkflowEndpoint - Endpoint for workflows.

Variables

This section is empty.

Functions

This section is empty.

Types

type ChatCompletionResponse

type ChatCompletionResponse struct {
	ID             string   `json:"id,omitempty"`              // Agent thought ID. Each Agent iteration will have a unique id.
	Event          string   `json:"event,omitempty"`           // SSE event name.
	MessageID      string   `json:"message_id,omitempty"`      // Message unique ID.
	ConversationID string   `json:"conversation_id,omitempty"` // Session ID.
	Mode           string   `json:"mode,omitempty"`            // App mode, `chat` or `completion`.
	Answer         string   `json:"answer"`                    // Full response content.
	Metadata       Metadata `json:"metadata,omitempty"`        // Message metadata.
	CreatedAt      int      `json:"created_at"`                // Message creation timestamp, such as: 1705395332.
}

ChatCompletionResponse - Response body from the CreateChatMessage or CreateCompletionMessage endpoint in blocking mode.

type ChatMessageRequest

type ChatMessageRequest struct {
	Query            string                 `json:"query"`                        // User input/question content.
	Inputs           map[string]interface{} `json:"inputs"`                       // Variables defined, contains multiple key/value pairs.
	ResponseMode     ResponseMode           `json:"response_mode"`                // Response mode, `streaming`(recommended) or `blocking`.
	User             string                 `json:"user"`                         // Identity of the end user.
	Files            []File                 `json:"files"`                        // Uploaded files.
	ConversationID   string                 `json:"conversation_id,omitempty"`    // Conversation ID, optional.
	AutoGenerateName *bool                  `json:"auto_generate_name,omitempty"` // Automatically generate titles, by default `true`.
}

ChatMessageRequest - Request body for creating a chat message.

type ChunkChatCompletionResponse

type ChunkChatCompletionResponse struct {
	ID             string   `json:"id,omitempty"`              // Agent thought ID. Each Agent iteration will have a unique id.
	Event          string   `json:"event,omitempty"`           // SSE event name.
	TaskID         string   `json:"task_id,omitempty"`         // Task ID, used for request tracking and the stop response interface below.
	MessageID      string   `json:"message_id,omitempty"`      // Message unique ID.
	ConversationID string   `json:"conversation_id,omitempty"` // Session ID.
	Answer         string   `json:"answer,omitempty"`          // Block response content.
	Position       int      `json:"position,omitempty"`        // The position of agent_thought in the message, such as the first iteration position is 1.
	Thought        string   `json:"thought,omitempty"`         // The agent's thoughts.
	Observation    string   `json:"observation,omitempty"`     // The result returned by the tool call.
	Tool           string   `json:"tool,omitempty"`            // List of tools to use, separate multiple tools with.
	ToolInput      string   `json:"tool_input,omitempty"`      // Tool input, a string in JSON format (object).
	MessageFiles   []string `json:"message_files,omitempty"`   // Current agent_thought associated file ID.
	Type           string   `json:"type,omitempty"`            // File type, currently only image.
	BelongsTo      string   `json:"belongs_to,omitempty"`      // File owner, user or assistant. This interface returns only assistant.
	URL            string   `json:"url,omitempty"`             // File access address.
	Metadata       Metadata `json:"metadata,omitempty"`        // Message metadata.
	Audio          string   `json:"audio,omitempty"`           // The audio block after speech synthesis is encoded with Base64 text content.
	Status         int      `json:"status,omitempty"`          // HTTP status code.
	Code           string   `json:"code,omitempty"`            // Error code.
	Message        string   `json:"message,omitempty"`         // Error message.
	CreatedAt      int      `json:"created_at,omitempty"`      // Message creation timestamp, such as: 1705395332.
}

ChunkChatCompletionResponse - Response body from the CreateChatMessageStream or CreateCompletionMessageStream endpoint in streaming mode.

type ChunkCompletionResponse

type ChunkCompletionResponse struct {
	TaskID        string `json:"task_id"`                   // Task ID, used for request tracking and the stop response interface below.
	WorkflowRunID string `json:"workflow_run_id,omitempty"` // Workflow execution ID.
	MessageID     string `json:"message_id,omitempty"`      // Message unique ID.
	Event         string `json:"event,omitempty"`           // Fixed to workflow_started.
	Audio         string `json:"audio,omitempty"`           // The audio block after speech synthesis is encoded with Base64 text content.
	Data          struct {
		ID                string                   `json:"id"`                            // Workflow execution ID or Node execution ID.
		WorkflowID        string                   `json:"workflow_id,omitempty"`         // Associated Workflow ID.
		SequenceNumber    int                      `json:"sequence_number,omitempty"`     // Self-incrementing sequence number, self-incrementing within the App, starting from 1.
		NodeID            string                   `json:"node_id,omitempty"`             // Node ID.
		NodeType          string                   `json:"node_type,omitempty"`           // Node type, such as: chat, completion, tool, etc.
		Title             string                   `json:"title,omitempty"`               // Node name.
		Index             int                      `json:"index,omitempty"`               // Execution sequence number, used to display the Tracing Node sequence.
		PredecessorNodeID string                   `json:"predecessor_node_id,omitempty"` // Prefix node ID, used to display the execution path on the canvas.
		Inputs            []map[string]interface{} `json:"inputs,omitempty"`              // All the previous node variables used in the node.
		ProcessData       map[string]interface{}   `json:"process_data,omitempty"`        // Optional Node process data.
		Outputs           map[string]interface{}   `json:"outputs,omitempty"`             // Optional Output content.
		Status            string                   `json:"status,omitempty"`              // Execution status running/succeeded/failed/stopped.
		Error             string                   `json:"error,omitempty"`               // Optional The reason for the error.
		ElapsedTime       float64                  `json:"elapsed_time,omitempty"`        // Optional time consumed (s).
		ExecutionMetadata map[string]interface{}   `json:"execution_metadata,omitempty"`  // Metadata.
		TotalTokens       int                      `json:"total_tokens,omitempty"`        // Optional Total tokens used.
		TotalPrice        float64                  `json:"total_price,omitempty"`         // Optional Total cost.
		Currency          string                   `json:"currency,omitempty"`            // Currency, such as USD/RMB.
		TotalSteps        int                      `json:"total_steps,omitempty"`         // Total number of steps (redundant), default 0.
		CreatedAt         int                      `json:"created_at"`                    // Start time.
		FinishedAt        int                      `json:"finished_at,omitempty"`         // End time.
	} `json:"data,omitempty"` // Details.
	CreatedAt int `json:"created_at,omitempty"` // Creation timestamp, such as: 1705395332.
}

ChunkCompletionResponse - Response body from the RunWorkflowStream endpoint in streaming mode.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client - Dify client for interacting with the API.

func NewClient

func NewClient(config ClientConfig) (*Client, error)

NewClient - Creates and returns a new Dify client.

func (*Client) CreateChatMessage

func (c *Client) CreateChatMessage(ctx context.Context, req ChatMessageRequest) (*ChatCompletionResponse, error)

CreateChatMessage - Creates a chat message in blocking mode.

func (*Client) CreateChatMessageStream

func (c *Client) CreateChatMessageStream(ctx context.Context, req ChatMessageRequest) (<-chan ChunkChatCompletionResponse, error)

CreateChatMessageStream - Creates a chat message in streaming mode.

func (*Client) CreateCompletionMessage

func (c *Client) CreateCompletionMessage(ctx context.Context, req CompletionMessageRequest) (*ChatCompletionResponse, error)

CreateCompletionMessage - Creates a completion message in blocking mode.

func (*Client) CreateCompletionMessageStream

func (c *Client) CreateCompletionMessageStream(ctx context.Context, req CompletionMessageRequest) (<-chan ChunkChatCompletionResponse, error)

CreateCompletionMessageStream - Creates a completion message in streaming mode.

func (*Client) RunWorkflow

func (c *Client) RunWorkflow(ctx context.Context, req RunWorkflowRequest) (*CompletionResponse, error)

RunWorkflow - Runs a workflow in blocking mode.

func (*Client) RunWorkflowStream

func (c *Client) RunWorkflowStream(ctx context.Context, req RunWorkflowRequest) (<-chan ChunkCompletionResponse, error)

RunWorkflowStream - Runs a workflow in streaming mode.

type ClientConfig

type ClientConfig struct {
	BaseURL string // The base URL of the Dify API.
	APIKey  string // The API key for authentication.
}

ClientConfig - Configuration for the Dify client.

type CompletionMessageRequest

type CompletionMessageRequest struct {
	Inputs       map[string]interface{} `json:"inputs"`        // User input/question content.
	ResponseMode ResponseMode           `json:"response_mode"` // Response mode, `streaming`(recommended) or `blocking`.
	User         string                 `json:"user"`          // Identity of the end user.
	Files        []File                 `json:"files"`         // Uploaded files.
}

CompletionMessageRequest - Request body for creating a completion message.

type CompletionResponse

type CompletionResponse struct {
	WorkflowRunID string `json:"workflow_run_id"` // Workflow execution ID.
	TaskID        string `json:"task_id"`         // Task ID, used for request tracking and the stop response interface below.
	Data          struct {
		ID          string                 `json:"id"`           // Workflow execution ID.
		WorkflowID  string                 `json:"workflow_id"`  // Associated Workflow ID.
		Status      string                 `json:"status"`       // Execution status , running/succeeded/failed/stopped.
		Outputs     map[string]interface{} `json:"outputs"`      // Optional Output content.
		Error       string                 `json:"error"`        // Optional The reason for the error.
		ElapsedTime float64                `json:"elapsed_time"` // Optional time consumed (s).
		TotalTokens int                    `json:"total_tokens"` // Optional Total tokens used.
		TotalSteps  int                    `json:"total_steps"`  // Total number of steps (redundant), default 0.
		CreatedAt   int                    `json:"created_at"`   // Start time.
		FinishedAt  int                    `json:"finished_at"`  // End time.
	} `json:"data"` // Details.
}

CompletionResponse - Response body from the RunWorkflow endpoint in blocking mode.

type File

type File struct {
	Type           string `json:"type"`                     // Supported types, `image` only.
	TransferMethod string `json:"transfer_method"`          // Delivery method, `remote_url` or `local_file`.
	Url            string `json:"url,omitempty"`            // Image URL.
	UploadFileID   string `json:"upload_file_id,omitempty"` // Upload file ID.
}

File - Uploaded File

type Metadata

type Metadata struct {
	Usage              Usage               `json:"usage"`                         // Model usage information.
	RetrieverResources []RetrieverResource `json:"retriever_resources,omitempty"` // List of references and attributed segments.
}

Metadata - Message metadata.

type ResponseMode

type ResponseMode string

ResponseMode - Response mode, `streaming` or `blocking`.

const (
	BlockingMode  ResponseMode = "blocking"  // Blocking response.
	StreamingMode ResponseMode = "streaming" // Streaming response.
)

type RetrieverResource

type RetrieverResource struct {
	Position     int     `json:"position"`      // Position of the reference in the message.
	DatasetID    string  `json:"dataset_id"`    // ID of the dataset.
	DatasetName  string  `json:"dataset_name"`  // Name of the dataset.
	DocumentID   string  `json:"document_id"`   // ID of the document.
	DocumentName string  `json:"document_name"` // Name of the document.
	SegmentID    string  `json:"segment_id"`    // ID of the segment.
	Score        float64 `json:"score"`         // Score of the segment.
	Content      string  `json:"content"`       // Content of the segment.
}

RetrieverResource - Message references and attributed segments.

type RunWorkflowRequest

type RunWorkflowRequest struct {
	Inputs       map[string]interface{} `json:"inputs"`        // User input/question content.
	ResponseMode ResponseMode           `json:"response_mode"` // Response mode, `streaming`(recommended) or `blocking`.
	User         string                 `json:"user"`          // Identity of the end user.
	Files        []File                 `json:"files"`         // Uploaded files.
}

RunWorkflowRequest - Request body for running a workflow.

type Usage

type Usage struct {
	PromptTokens        int     `json:"prompt_tokens"`         // Number of tokens in the prompt.
	PromptUnitPrice     string  `json:"prompt_unit_price"`     // Unit price of the prompt.
	PromptPriceUnit     string  `json:"prompt_price_unit"`     // Price unit of the prompt.
	PromptPrice         string  `json:"prompt_price"`          // Total price of the prompt.
	CompletionTokens    int     `json:"completion_tokens"`     // Number of tokens in the completion.
	CompletionUnitPrice string  `json:"completion_unit_price"` // Unit price of the completion.
	CompletionPriceUnit string  `json:"completion_price_unit"` // Price unit of the completion.
	CompletionPrice     string  `json:"completion_price"`      // Total price of the completion.
	TotalTokens         int     `json:"total_tokens"`          // Total number of tokens used.
	TotalPrice          string  `json:"total_price"`           // Total price of the request.
	Currency            string  `json:"currency"`              // Currency used for the request.
	Latency             float64 `json:"latency"`               // Latency of the request.
}

Usage - Model usage information.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL