Dify.ai integration (#5761)
This commit is contained in:
1 parent
074e5d7002
commit
d4ba4fd98a
18 files changed
+1377
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"claude-dev": patch
|
||||
---
|
||||
|
||||
Dify.ai api integration
|
||||
@@ -150,6 +150,7 @@ enum ApiProvider {
|
||||
ZAI = 31;
|
||||
VERCEL_AI_GATEWAY = 32;
|
||||
QWEN_CODE = 33;
|
||||
DIFY = 34;
|
||||
}
|
||||
|
||||
// Model info for OpenAI-compatible models
|
||||
@@ -259,6 +260,8 @@ message ModelsApiConfiguration {
|
||||
optional string lm_studio_max_tokens = 67;
|
||||
optional string vercel_ai_gateway_api_key = 68;
|
||||
optional string qwen_code_oauth_path = 69;
|
||||
optional string dify_api_key = 70;
|
||||
optional string dify_base_url = 71;
|
||||
|
||||
// Plan mode configurations
|
||||
optional ApiProvider plan_mode_api_provider = 100;
|
||||
|
||||
@@ -194,6 +194,8 @@ message ApiConfiguration {
|
||||
optional string lm_studio_max_tokens = 61;
|
||||
optional string vercel_ai_gateway_api_key = 62;
|
||||
optional string qwen_code_oauth_path = 63;
|
||||
optional string dify_api_key = 64;
|
||||
optional string dify_base_url = 65;
|
||||
|
||||
// Plan mode configurations
|
||||
optional string plan_mode_api_provider = 100;
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
import { Anthropic } from "@anthropic-ai/sdk"
|
||||
import { ApiHandlerOptions, ModelInfo } from "@shared/api"
|
||||
import { ApiHandler } from "../../core/api/index"
|
||||
import { ApiStream } from "../../core/api/transform/stream"
|
||||
|
||||
export class DifyHandler implements ApiHandler {
|
||||
private options: ApiHandlerOptions
|
||||
private baseUrl: string
|
||||
private apiKey: string
|
||||
private conversationId: string | null = null
|
||||
|
||||
constructor(options: ApiHandlerOptions) {
|
||||
this.options = options
|
||||
this.apiKey = options.difyApiKey || ""
|
||||
this.baseUrl = options.difyBaseUrl || ""
|
||||
|
||||
console.log("[DIFY DEBUG] Constructor called with:", {
|
||||
hasApiKey: !!this.apiKey,
|
||||
baseUrl: this.baseUrl,
|
||||
})
|
||||
|
||||
if (!this.apiKey) {
|
||||
throw new Error("Dify API key is required")
|
||||
}
|
||||
if (!this.baseUrl) {
|
||||
throw new Error("Dify base URL is required")
|
||||
}
|
||||
}
|
||||
|
||||
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
|
||||
console.log("[DIFY DEBUG] createMessage called with:", {
|
||||
systemPromptLength: systemPrompt?.length || 0,
|
||||
messagesCount: messages?.length || 0,
|
||||
})
|
||||
|
||||
// Convert messages to Dify format
|
||||
const query = this.convertMessagesToQuery(systemPrompt, messages)
|
||||
const requestBody = {
|
||||
inputs: {},
|
||||
query: query,
|
||||
response_mode: "streaming",
|
||||
conversation_id: this.conversationId || "",
|
||||
user: "cline-user", // A unique user identifier
|
||||
files: [],
|
||||
}
|
||||
|
||||
const fullUrl = `${this.baseUrl}/chat-messages`
|
||||
console.log("[DIFY DEBUG] Making request to:", fullUrl)
|
||||
console.log("[DIFY DEBUG] Request body:", JSON.stringify(requestBody, null, 2))
|
||||
console.log("[DIFY DEBUG] Current process environment variables (for proxy debugging):", process.env)
|
||||
|
||||
let response: Response
|
||||
try {
|
||||
response = await fetch(fullUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(requestBody),
|
||||
})
|
||||
} catch (error: any) {
|
||||
console.error("[DIFY DEBUG] Network error during fetch:", error)
|
||||
// Log more detailed error information if available (e.g., from undici)
|
||||
const cause = error.cause ? ` | Cause: ${error.cause}` : ""
|
||||
throw new Error(`Dify API network error: ${error.message}${cause}`)
|
||||
}
|
||||
|
||||
console.log("[DIFY DEBUG] Response status:", response.status)
|
||||
const headersObj: Record<string, string> = {}
|
||||
response.headers.forEach((value, key) => {
|
||||
headersObj[key] = value
|
||||
})
|
||||
console.log("[DIFY DEBUG] Response headers:", headersObj)
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text()
|
||||
console.error("[DIFY DEBUG] Error response:", errorText)
|
||||
throw new Error(`Dify API error: ${response.status} ${response.statusText} - ${errorText}`)
|
||||
}
|
||||
|
||||
if (!response.body) {
|
||||
throw new Error("No response body from Dify API")
|
||||
}
|
||||
|
||||
const reader = response.body.getReader()
|
||||
const decoder = new TextDecoder()
|
||||
let buffer = ""
|
||||
let fullText = ""
|
||||
|
||||
console.log("[DIFY DEBUG] Starting to read streaming response...")
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) {
|
||||
console.log("[DIFY DEBUG] Stream ended naturally")
|
||||
break
|
||||
}
|
||||
|
||||
const chunk = decoder.decode(value, { stream: true })
|
||||
console.log("[DIFY DEBUG] Raw chunk received:", JSON.stringify(chunk))
|
||||
|
||||
buffer += chunk
|
||||
const lines = buffer.split("\n")
|
||||
|
||||
// Keep the last incomplete line in the buffer
|
||||
buffer = lines.pop() || ""
|
||||
|
||||
for (const line of lines) {
|
||||
console.log("[DIFY DEBUG] Processing line:", JSON.stringify(line))
|
||||
|
||||
if (line.startsWith("data: ")) {
|
||||
const data = line.slice(6).trim()
|
||||
console.log("[DIFY DEBUG] Extracted data:", JSON.stringify(data))
|
||||
|
||||
if (data === "[DONE]") {
|
||||
console.log("[DIFY DEBUG] Received [DONE] signal")
|
||||
return // Explicitly return on [DONE]
|
||||
}
|
||||
|
||||
if (data === "") {
|
||||
console.log("[DIFY DEBUG] Empty data line, skipping")
|
||||
continue
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(data)
|
||||
console.log("[DIFY DEBUG] Parsed JSON:", parsed)
|
||||
|
||||
// Capture conversation_id as soon as it's available
|
||||
if (parsed.conversation_id && !this.conversationId) {
|
||||
this.conversationId = parsed.conversation_id
|
||||
console.log("[DIFY DEBUG] Captured conversation_id:", this.conversationId)
|
||||
}
|
||||
|
||||
// Handle different Dify event types based on actual Dify API
|
||||
if (parsed.event === "message") {
|
||||
console.log("[DIFY DEBUG] Message event, answer:", parsed.answer)
|
||||
// Dify sends the full text in each "answer" chunk, so we replace.
|
||||
if (typeof parsed.answer === "string") {
|
||||
fullText = parsed.answer
|
||||
console.log("[DIFY DEBUG] Updated fullText length:", fullText.length)
|
||||
yield {
|
||||
type: "text",
|
||||
text: fullText,
|
||||
}
|
||||
}
|
||||
} else if (parsed.event === "message_replace") {
|
||||
console.log("[DIFY DEBUG] Replace message event:", parsed)
|
||||
if (parsed.answer) {
|
||||
fullText = parsed.answer // Replace instead of append
|
||||
console.log("[DIFY DEBUG] Replaced fullText length:", fullText.length)
|
||||
yield {
|
||||
type: "text",
|
||||
text: fullText,
|
||||
}
|
||||
}
|
||||
} else if (parsed.event === "message_end") {
|
||||
console.log("[DIFY DEBUG] Message end event", parsed)
|
||||
// Message completed. Yield final text if we have any.
|
||||
if (fullText) {
|
||||
yield {
|
||||
type: "text",
|
||||
text: fullText,
|
||||
}
|
||||
}
|
||||
// Yield usage data if available
|
||||
if (parsed.usage) {
|
||||
yield {
|
||||
type: "usage",
|
||||
inputTokens: parsed.usage.prompt_tokens || 0,
|
||||
outputTokens: parsed.usage.completion_tokens || parsed.usage.total_tokens || 0,
|
||||
totalCost: parsed.usage.total_price || 0,
|
||||
}
|
||||
}
|
||||
return // End of stream
|
||||
} else if (parsed.event === "error") {
|
||||
console.error("[DIFY DEBUG] Error event:", parsed)
|
||||
throw new Error(`Dify API error: ${parsed.message || "Unknown error"}`)
|
||||
} else if (parsed.event === "workflow_started" || parsed.event === "workflow_finished") {
|
||||
console.log("[DIFY DEBUG] Workflow event:", parsed.event)
|
||||
// These are informational events, continue processing
|
||||
} else if (parsed.event === "node_started" || parsed.event === "node_finished") {
|
||||
console.log("[DIFY DEBUG] Node event:", parsed.event, parsed.data)
|
||||
// These are informational events, continue processing
|
||||
} else if (parsed.event === "ping") {
|
||||
console.log("[DIFY DEBUG] Ping event received, keeping connection alive.")
|
||||
// Ping event, do nothing
|
||||
} else {
|
||||
console.log("[DIFY DEBUG] Unknown event type:", parsed.event, "Full object:", parsed)
|
||||
// Try to extract text from other possible fields
|
||||
if (parsed.text) {
|
||||
fullText += parsed.text
|
||||
yield {
|
||||
type: "text",
|
||||
text: fullText,
|
||||
}
|
||||
} else if (parsed.content) {
|
||||
fullText += parsed.content
|
||||
yield {
|
||||
type: "text",
|
||||
text: fullText,
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn("[DIFY DEBUG] Failed to parse JSON:", data, "Error:", e)
|
||||
}
|
||||
} else if (line.trim() !== "") {
|
||||
console.log(
|
||||
"[DIFY DEBUG] Non-data line (not starting with 'data:'), trying to parse as direct JSON:",
|
||||
JSON.stringify(line),
|
||||
)
|
||||
// Try to parse as direct JSON (fallback for non-SSE responses, though Dify uses SSE)
|
||||
try {
|
||||
const parsed = JSON.parse(line.trim())
|
||||
console.log("[DIFY DEBUG] Parsed direct JSON:", parsed)
|
||||
|
||||
// Handle the same event types as above
|
||||
if (parsed.event === "message" && parsed.answer) {
|
||||
fullText += parsed.answer
|
||||
yield {
|
||||
type: "text",
|
||||
text: fullText,
|
||||
}
|
||||
} else if (parsed.event === "message_end") {
|
||||
if (fullText) {
|
||||
yield {
|
||||
type: "text",
|
||||
text: fullText,
|
||||
}
|
||||
}
|
||||
return
|
||||
} else if (parsed.event === "error") {
|
||||
console.error("[DIFY DEBUG] Direct JSON Error event:", parsed)
|
||||
throw new Error(`Dify API error: ${parsed.message || "Unknown error"}`)
|
||||
}
|
||||
} catch (e) {
|
||||
// Not JSON, continue
|
||||
console.log("[DIFY DEBUG] Line is not direct JSON, continuing")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock()
|
||||
console.log("[DIFY DEBUG] Stream reader released")
|
||||
}
|
||||
}
|
||||
|
||||
private convertMessagesToQuery(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): string {
|
||||
// Dify's context is managed by `conversation_id`. The `query` should be the last user message.
|
||||
// The system prompt is typically configured in the Dify App itself.
|
||||
const lastUserMessage = messages.filter((m) => m.role === "user").pop()
|
||||
|
||||
if (!lastUserMessage) {
|
||||
return "" // Should not happen in normal flow
|
||||
}
|
||||
|
||||
const userQuery = Array.isArray(lastUserMessage.content)
|
||||
? lastUserMessage.content.map((c) => ("text" in c ? c.text : "")).join("\n")
|
||||
: (lastUserMessage.content as string)
|
||||
|
||||
// Only prepend the system prompt if it's the very first message of a new conversation.
|
||||
if (!this.conversationId && systemPrompt) {
|
||||
console.log("[DIFY DEBUG] Prepending system prompt for new conversation.")
|
||||
return `${systemPrompt}\n\n---\n\n${userQuery}`
|
||||
}
|
||||
|
||||
return userQuery
|
||||
}
|
||||
|
||||
getModel(): { id: string; info: ModelInfo } {
|
||||
return {
|
||||
id: "dify-workflow",
|
||||
info: {
|
||||
maxTokens: 8192,
|
||||
contextWindow: 128000,
|
||||
supportsImages: true,
|
||||
supportsPromptCache: false,
|
||||
inputPrice: 0,
|
||||
outputPrice: 0,
|
||||
description: "Dify workflow - model selection is configured in your Dify application",
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import { CerebrasHandler } from "./providers/cerebras"
|
||||
import { ClaudeCodeHandler } from "./providers/claude-code"
|
||||
import { ClineHandler } from "./providers/cline"
|
||||
import { DeepSeekHandler } from "./providers/deepseek"
|
||||
import { DifyHandler } from "./providers/dify"
|
||||
import { DoubaoHandler } from "./providers/doubao"
|
||||
import { FireworksHandler } from "./providers/fireworks"
|
||||
import { GeminiHandler } from "./providers/gemini"
|
||||
@@ -345,6 +346,15 @@ function createHandlerForProvider(
|
||||
huaweiCloudMaasModelInfo:
|
||||
mode === "plan" ? options.planModeHuaweiCloudMaasModelInfo : options.actModeHuaweiCloudMaasModelInfo,
|
||||
})
|
||||
case "dify": // Add Dify.ai handler
|
||||
console.log("[DIFY DEBUG] Instantiating DifyHandler with options:", {
|
||||
difyApiKeyPresent: !!options.difyApiKey,
|
||||
difyBaseUrl: options.difyBaseUrl,
|
||||
})
|
||||
return new DifyHandler({
|
||||
difyApiKey: options.difyApiKey,
|
||||
difyBaseUrl: options.difyBaseUrl,
|
||||
})
|
||||
case "vercel-ai-gateway":
|
||||
return new VercelAIGatewayHandler({
|
||||
vercelAiGatewayApiKey: options.vercelAiGatewayApiKey,
|
||||
|
||||
@@ -0,0 +1,655 @@
|
||||
import { Anthropic } from "@anthropic-ai/sdk"
|
||||
import { ApiHandlerOptions, ModelInfo } from "../../../shared/api"
|
||||
import { ApiHandler } from "../index"
|
||||
import { ApiStream } from "../transform/stream"
|
||||
|
||||
// Dify API Response Types
|
||||
export interface DifyFileResponse {
|
||||
id: string
|
||||
name: string
|
||||
size: number
|
||||
extension: string
|
||||
mime_type: string
|
||||
created_by: string
|
||||
created_at: number
|
||||
}
|
||||
|
||||
export interface DifyMessage {
|
||||
id: string
|
||||
conversation_id: string
|
||||
inputs: Record<string, any>
|
||||
query: string
|
||||
message_files: Array<{
|
||||
id: string
|
||||
type: string
|
||||
url: string
|
||||
belongs_to: string
|
||||
}>
|
||||
answer: string
|
||||
created_at: number
|
||||
feedback?: {
|
||||
rating: string
|
||||
}
|
||||
retriever_resources?: any[]
|
||||
}
|
||||
|
||||
interface DifyHistoryResponse {
|
||||
data: DifyMessage[]
|
||||
has_more: boolean
|
||||
limit: number
|
||||
}
|
||||
|
||||
interface DifyConversation {
|
||||
id: string
|
||||
name: string
|
||||
inputs: Record<string, any>
|
||||
status: string
|
||||
introduction: string
|
||||
created_at: number
|
||||
updated_at: number
|
||||
}
|
||||
|
||||
interface DifyConversationsResponse {
|
||||
data: DifyConversation[]
|
||||
has_more: boolean
|
||||
limit: number
|
||||
}
|
||||
|
||||
interface DifyConversationResponse {
|
||||
id: string
|
||||
name: string
|
||||
inputs: Record<string, any>
|
||||
status: string
|
||||
introduction: string
|
||||
created_at: number
|
||||
updated_at: number
|
||||
}
|
||||
|
||||
export class DifyHandler implements ApiHandler {
|
||||
private options: ApiHandlerOptions
|
||||
private baseUrl: string
|
||||
private apiKey: string
|
||||
private conversationId: string | null = null
|
||||
private currentTaskId: string | null = null
|
||||
private abortController: AbortController | null = null
|
||||
|
||||
constructor(options: ApiHandlerOptions) {
|
||||
this.options = options
|
||||
this.apiKey = options.difyApiKey || ""
|
||||
this.baseUrl = options.difyBaseUrl || ""
|
||||
|
||||
console.log("[DIFY DEBUG] Constructor called with:", {
|
||||
hasApiKey: !!this.apiKey,
|
||||
baseUrl: this.baseUrl,
|
||||
})
|
||||
|
||||
if (!this.apiKey) {
|
||||
throw new Error("Dify API key is required")
|
||||
}
|
||||
if (!this.baseUrl) {
|
||||
throw new Error("Dify base URL is required")
|
||||
}
|
||||
}
|
||||
|
||||
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
|
||||
console.log("[DIFY DEBUG] createMessage called with:", {
|
||||
systemPromptLength: systemPrompt?.length || 0,
|
||||
messagesCount: messages?.length || 0,
|
||||
})
|
||||
|
||||
// Convert messages to Dify format
|
||||
const query = this.convertMessagesToQuery(systemPrompt, messages)
|
||||
const requestBody = {
|
||||
inputs: {},
|
||||
query: query,
|
||||
response_mode: "streaming",
|
||||
conversation_id: this.conversationId || "",
|
||||
user: "cline-user", // A unique user identifier
|
||||
files: [],
|
||||
}
|
||||
|
||||
const fullUrl = `${this.baseUrl}/chat-messages`
|
||||
console.log("[DIFY DEBUG] Making request to:", fullUrl)
|
||||
console.log("[DIFY DEBUG] Request body:", JSON.stringify(requestBody, null, 2))
|
||||
|
||||
let response: Response
|
||||
try {
|
||||
response = await fetch(fullUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(requestBody),
|
||||
})
|
||||
} catch (error: any) {
|
||||
console.error("[DIFY DEBUG] Network error during fetch:", error)
|
||||
const cause = error.cause ? ` | Cause: ${error.cause}` : ""
|
||||
throw new Error(`Dify API network error: ${error.message}${cause}`)
|
||||
}
|
||||
|
||||
console.log("[DIFY DEBUG] Response status:", response.status)
|
||||
const headersObj: Record<string, string> = {}
|
||||
response.headers.forEach((value, key) => {
|
||||
headersObj[key] = value
|
||||
})
|
||||
console.log("[DIFY DEBUG] Response headers:", headersObj)
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text()
|
||||
console.error("[DIFY DEBUG] Error response:", errorText)
|
||||
throw new Error(`Dify API error: ${response.status} ${response.statusText} - ${errorText}`)
|
||||
}
|
||||
|
||||
if (!response.body) {
|
||||
throw new Error("No response body from Dify API")
|
||||
}
|
||||
|
||||
const reader = response.body.getReader()
|
||||
const decoder = new TextDecoder()
|
||||
let buffer = ""
|
||||
let fullText = ""
|
||||
let hasYieldedContent = false
|
||||
const processedEvents: string[] = []
|
||||
let lastEventTime = Date.now()
|
||||
|
||||
console.log("[DIFY DEBUG] Starting to read streaming response...")
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) {
|
||||
console.log("[DIFY DEBUG] Stream ended naturally")
|
||||
console.log(
|
||||
"[DIFY DEBUG] Final state - hasYieldedContent:",
|
||||
hasYieldedContent,
|
||||
"fullText length:",
|
||||
fullText.length,
|
||||
"processedEvents:",
|
||||
processedEvents,
|
||||
)
|
||||
break
|
||||
}
|
||||
|
||||
const chunk = decoder.decode(value, { stream: true })
|
||||
console.log("[DIFY DEBUG] Raw chunk received:", JSON.stringify(chunk))
|
||||
|
||||
buffer += chunk
|
||||
const lines = buffer.split("\n")
|
||||
|
||||
// Keep the last incomplete line in the buffer
|
||||
buffer = lines.pop() || ""
|
||||
|
||||
for (const line of lines) {
|
||||
console.log("[DIFY DEBUG] Processing line:", JSON.stringify(line))
|
||||
|
||||
if (line.startsWith("data: ")) {
|
||||
const data = line.slice(6).trim()
|
||||
console.log("[DIFY DEBUG] Extracted data:", JSON.stringify(data))
|
||||
|
||||
if (data === "[DONE]") {
|
||||
console.log("[DIFY DEBUG] Received [DONE] signal")
|
||||
break
|
||||
}
|
||||
|
||||
if (data === "") {
|
||||
console.log("[DIFY DEBUG] Empty data line, skipping")
|
||||
continue
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(data)
|
||||
console.log("[DIFY DEBUG] Parsed JSON:", parsed)
|
||||
processedEvents.push(parsed.event || "unknown")
|
||||
lastEventTime = Date.now()
|
||||
|
||||
// Capture conversation_id as soon as it's available
|
||||
if (parsed.conversation_id && !this.conversationId) {
|
||||
this.conversationId = parsed.conversation_id
|
||||
console.log("[DIFY DEBUG] Captured conversation_id:", this.conversationId)
|
||||
}
|
||||
|
||||
// Handle different Dify event types based on actual Dify API
|
||||
if (parsed.event === "message") {
|
||||
console.log("[DIFY DEBUG] Message event, answer:", parsed.answer)
|
||||
// Dify sends the full text in each "answer" chunk, so we replace.
|
||||
if (typeof parsed.answer === "string") {
|
||||
fullText = parsed.answer
|
||||
console.log("[DIFY DEBUG] Updated fullText length:", fullText.length)
|
||||
yield {
|
||||
type: "text",
|
||||
text: fullText,
|
||||
}
|
||||
hasYieldedContent = true
|
||||
}
|
||||
} else if (parsed.event === "message_replace") {
|
||||
console.log("[DIFY DEBUG] Replace message event:", parsed)
|
||||
if (parsed.answer) {
|
||||
fullText = parsed.answer // Replace instead of append
|
||||
console.log("[DIFY DEBUG] Replaced fullText length:", fullText.length)
|
||||
yield {
|
||||
type: "text",
|
||||
text: fullText,
|
||||
}
|
||||
hasYieldedContent = true
|
||||
}
|
||||
} else if (parsed.event === "message_end") {
|
||||
console.log("[DIFY DEBUG] Message end event", parsed)
|
||||
// Message completed. Yield final text if we have any.
|
||||
if (fullText) {
|
||||
yield {
|
||||
type: "text",
|
||||
text: fullText,
|
||||
}
|
||||
hasYieldedContent = true
|
||||
}
|
||||
// Yield usage data if available
|
||||
if (parsed.usage) {
|
||||
yield {
|
||||
type: "usage",
|
||||
inputTokens: parsed.usage.prompt_tokens || 0,
|
||||
outputTokens: parsed.usage.completion_tokens || parsed.usage.total_tokens || 0,
|
||||
totalCost: parsed.usage.total_price || 0,
|
||||
}
|
||||
}
|
||||
return // End of stream
|
||||
} else if (parsed.event === "error") {
|
||||
console.error("[DIFY DEBUG] Error event:", parsed)
|
||||
throw new Error(`Dify API error: ${parsed.message || "Unknown error"}`)
|
||||
} else if (parsed.event === "workflow_started" || parsed.event === "workflow_finished") {
|
||||
console.log("[DIFY DEBUG] Workflow event:", parsed.event)
|
||||
// These are informational events, continue processing
|
||||
} else if (parsed.event === "node_started" || parsed.event === "node_finished") {
|
||||
console.log("[DIFY DEBUG] Node event:", parsed.event, parsed.data)
|
||||
// These are informational events, continue processing
|
||||
} else if (parsed.event === "ping") {
|
||||
console.log("[DIFY DEBUG] Ping event received, keeping connection alive.")
|
||||
// Ping event, do nothing
|
||||
} else {
|
||||
console.log("[DIFY DEBUG] Unknown event type:", parsed.event, "Full object:", parsed)
|
||||
// Try to extract text from other possible fields
|
||||
if (parsed.text) {
|
||||
fullText += parsed.text
|
||||
yield {
|
||||
type: "text",
|
||||
text: fullText,
|
||||
}
|
||||
hasYieldedContent = true
|
||||
} else if (parsed.content) {
|
||||
fullText += parsed.content
|
||||
yield {
|
||||
type: "text",
|
||||
text: fullText,
|
||||
}
|
||||
hasYieldedContent = true
|
||||
} else if (parsed.answer) {
|
||||
// Fallback: some events might have answer field even if not "message" type
|
||||
fullText += parsed.answer
|
||||
yield {
|
||||
type: "text",
|
||||
text: fullText,
|
||||
}
|
||||
hasYieldedContent = true
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn("[DIFY DEBUG] Failed to parse JSON:", data, "Error:", e)
|
||||
}
|
||||
} else if (line.trim() !== "") {
|
||||
console.log(
|
||||
"[DIFY DEBUG] Non-data line (not starting with 'data:'), trying to parse as direct JSON:",
|
||||
JSON.stringify(line),
|
||||
)
|
||||
// Try to parse as direct JSON (fallback for non-SSE responses, though Dify uses SSE)
|
||||
try {
|
||||
const parsed = JSON.parse(line.trim())
|
||||
console.log("[DIFY DEBUG] Parsed direct JSON:", parsed)
|
||||
processedEvents.push(parsed.event || "direct-json")
|
||||
|
||||
// Handle the same event types as above
|
||||
if (parsed.event === "message" && parsed.answer) {
|
||||
fullText += parsed.answer
|
||||
yield {
|
||||
type: "text",
|
||||
text: fullText,
|
||||
}
|
||||
hasYieldedContent = true
|
||||
} else if (parsed.event === "message_end") {
|
||||
if (fullText) {
|
||||
yield {
|
||||
type: "text",
|
||||
text: fullText,
|
||||
}
|
||||
hasYieldedContent = true
|
||||
}
|
||||
return
|
||||
} else if (parsed.event === "error") {
|
||||
console.error("[DIFY DEBUG] Direct JSON Error event:", parsed)
|
||||
throw new Error(`Dify API error: ${parsed.message || "Unknown error"}`)
|
||||
} else if (parsed.answer || parsed.text || parsed.content) {
|
||||
// Fallback for any content in direct JSON
|
||||
const content = parsed.answer || parsed.text || parsed.content
|
||||
fullText += content
|
||||
yield {
|
||||
type: "text",
|
||||
text: fullText,
|
||||
}
|
||||
hasYieldedContent = true
|
||||
}
|
||||
} catch (e) {
|
||||
// Not JSON, continue
|
||||
console.log("[DIFY DEBUG] Line is not direct JSON, continuing")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Final check - if we haven't yielded any content, provide diagnostic information
|
||||
if (!hasYieldedContent) {
|
||||
const diagnosticInfo = {
|
||||
processedEvents,
|
||||
finalFullTextLength: fullText.length,
|
||||
finalFullText: fullText,
|
||||
streamDuration: Date.now() - lastEventTime,
|
||||
conversationId: this.conversationId,
|
||||
}
|
||||
console.error("[DIFY DEBUG] No content was yielded! Diagnostic info:", diagnosticInfo)
|
||||
|
||||
// If we have any accumulated text at all, yield it as a fallback
|
||||
if (fullText.trim()) {
|
||||
console.log("[DIFY DEBUG] Yielding accumulated text as fallback:", fullText)
|
||||
yield {
|
||||
type: "text",
|
||||
text: fullText,
|
||||
}
|
||||
} else {
|
||||
// Provide a more informative error
|
||||
throw new Error(
|
||||
`Dify API did not provide any assistant messages. ` +
|
||||
`Events processed: [${processedEvents.join(", ")}]. ` +
|
||||
`Check your Dify application configuration and ensure it's properly set up to return responses. ` +
|
||||
`API URL: ${fullUrl}. Conversation ID: ${this.conversationId || "none"}.`,
|
||||
)
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock()
|
||||
console.log("[DIFY DEBUG] Stream reader released")
|
||||
}
|
||||
}
|
||||
|
||||
private convertMessagesToQuery(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): string {
|
||||
// Dify's context is managed by `conversation_id`. The `query` should be the last user message.
|
||||
// The system prompt is typically configured in the Dify App itself.
|
||||
const lastUserMessage = messages.filter((m) => m.role === "user").pop()
|
||||
|
||||
if (!lastUserMessage) {
|
||||
return "" // Should not happen in normal flow
|
||||
}
|
||||
|
||||
const userQuery = Array.isArray(lastUserMessage.content)
|
||||
? lastUserMessage.content.map((c) => ("text" in c ? c.text : "")).join("\n")
|
||||
: (lastUserMessage.content as string)
|
||||
|
||||
// Only prepend the system prompt if it's the very first message of a new conversation.
|
||||
if (!this.conversationId && systemPrompt) {
|
||||
console.log("[DIFY DEBUG] Prepending system prompt for new conversation.")
|
||||
return `${systemPrompt}\n\n---\n\n${userQuery}`
|
||||
}
|
||||
|
||||
return userQuery
|
||||
}
|
||||
|
||||
getModel(): { id: string; info: ModelInfo } {
|
||||
return {
|
||||
id: "dify-workflow",
|
||||
info: {
|
||||
maxTokens: 8192,
|
||||
contextWindow: 128000,
|
||||
supportsImages: true,
|
||||
supportsPromptCache: false,
|
||||
inputPrice: 0,
|
||||
outputPrice: 0,
|
||||
description: "Dify workflow - model selection is configured in your Dify application",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Additional Dify API Methods
|
||||
|
||||
/**
|
||||
* Upload a file for use in conversations
|
||||
* @param file File buffer to upload
|
||||
* @param filename Name of the file
|
||||
* @param user User identifier (defaults to "cline-user")
|
||||
* @returns Promise with file upload response
|
||||
*/
|
||||
async uploadFile(file: Buffer, filename: string, user: string = "cline-user"): Promise<DifyFileResponse> {
|
||||
const formData = new FormData()
|
||||
formData.append("file", new Blob([new Uint8Array(file)]), filename)
|
||||
formData.append("user", user)
|
||||
|
||||
const response = await fetch(`${this.baseUrl}/files/upload`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
},
|
||||
body: formData,
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text()
|
||||
throw new Error(`Dify file upload error: ${response.status} ${response.statusText} - ${errorText}`)
|
||||
}
|
||||
|
||||
return response.json()
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop generation for a specific task
|
||||
* @param taskId Task ID from streaming response
|
||||
* @param user User identifier (defaults to "cline-user")
|
||||
* @returns Promise that resolves when generation is stopped
|
||||
*/
|
||||
async stopGeneration(taskId: string, user: string = "cline-user"): Promise<void> {
|
||||
const response = await fetch(`${this.baseUrl}/chat-messages/${taskId}/stop`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ user }),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text()
|
||||
throw new Error(`Dify stop generation error: ${response.status} ${response.statusText} - ${errorText}`)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get conversation history messages with pagination
|
||||
* @param conversationId Conversation ID
|
||||
* @param user User identifier (defaults to "cline-user")
|
||||
* @param firstId First message ID for pagination (optional)
|
||||
* @param limit Number of messages to return (default: 20)
|
||||
* @returns Promise with conversation history
|
||||
*/
|
||||
async getConversationHistory(
|
||||
conversationId: string,
|
||||
user: string = "cline-user",
|
||||
firstId?: string,
|
||||
limit: number = 20,
|
||||
): Promise<DifyHistoryResponse> {
|
||||
const params = new URLSearchParams({ user, limit: limit.toString() })
|
||||
if (firstId) {
|
||||
params.append("first_id", firstId)
|
||||
}
|
||||
|
||||
const response = await fetch(`${this.baseUrl}/conversations/${conversationId}/messages?${params}`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
},
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text()
|
||||
throw new Error(`Dify get conversation history error: ${response.status} ${response.statusText} - ${errorText}`)
|
||||
}
|
||||
|
||||
return response.json()
|
||||
}
|
||||
|
||||
/**
|
||||
* Get list of conversations for a user
|
||||
* @param user User identifier (defaults to "cline-user")
|
||||
* @param lastId Last conversation ID for pagination (optional)
|
||||
* @param limit Number of conversations to return (default: 20)
|
||||
* @param sortBy Sort field (default: "-updated_at")
|
||||
* @returns Promise with conversations list
|
||||
*/
|
||||
async getConversations(
|
||||
user: string = "cline-user",
|
||||
lastId?: string,
|
||||
limit: number = 20,
|
||||
sortBy: string = "-updated_at",
|
||||
): Promise<DifyConversationsResponse> {
|
||||
const params = new URLSearchParams({
|
||||
user,
|
||||
limit: limit.toString(),
|
||||
sort_by: sortBy,
|
||||
})
|
||||
if (lastId) {
|
||||
params.append("last_id", lastId)
|
||||
}
|
||||
|
||||
const response = await fetch(`${this.baseUrl}/conversations?${params}`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
},
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text()
|
||||
throw new Error(`Dify get conversations error: ${response.status} ${response.statusText} - ${errorText}`)
|
||||
}
|
||||
|
||||
return response.json()
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a conversation
|
||||
* @param conversationId Conversation ID to delete
|
||||
* @param user User identifier (defaults to "cline-user")
|
||||
* @returns Promise that resolves when conversation is deleted
|
||||
*/
|
||||
async deleteConversation(conversationId: string, user: string = "cline-user"): Promise<void> {
|
||||
const response = await fetch(`${this.baseUrl}/conversations/${conversationId}`, {
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ user }),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text()
|
||||
throw new Error(`Dify delete conversation error: ${response.status} ${response.statusText} - ${errorText}`)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Rename a conversation
|
||||
* @param conversationId Conversation ID to rename
|
||||
* @param user User identifier (defaults to "cline-user")
|
||||
* @param name New conversation name (optional if auto_generate is true)
|
||||
* @param autoGenerate Whether to auto-generate the name (default: false)
|
||||
* @returns Promise with updated conversation details
|
||||
*/
|
||||
async renameConversation(
|
||||
conversationId: string,
|
||||
user: string = "cline-user",
|
||||
name?: string,
|
||||
autoGenerate: boolean = false,
|
||||
): Promise<DifyConversationResponse> {
|
||||
const body: any = { user, auto_generate: autoGenerate }
|
||||
if (name) {
|
||||
body.name = name
|
||||
}
|
||||
|
||||
const response = await fetch(`${this.baseUrl}/conversations/${conversationId}/name`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text()
|
||||
throw new Error(`Dify rename conversation error: ${response.status} ${response.statusText} - ${errorText}`)
|
||||
}
|
||||
|
||||
return response.json()
|
||||
}
|
||||
|
||||
/**
|
||||
* Submit feedback for a message
|
||||
* @param messageId Message ID to provide feedback for
|
||||
* @param rating Rating: "like" or "dislike"
|
||||
* @param content Optional feedback content
|
||||
* @param user User identifier (defaults to "cline-user")
|
||||
* @returns Promise that resolves when feedback is submitted
|
||||
*/
|
||||
async submitMessageFeedback(
|
||||
messageId: string,
|
||||
rating: "like" | "dislike",
|
||||
content?: string,
|
||||
user: string = "cline-user",
|
||||
): Promise<void> {
|
||||
const body: any = { rating, user }
|
||||
if (content) {
|
||||
body.content = content
|
||||
}
|
||||
|
||||
const response = await fetch(`${this.baseUrl}/messages/${messageId}/feedbacks`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text()
|
||||
throw new Error(`Dify submit feedback error: ${response.status} ${response.statusText} - ${errorText}`)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current conversation ID
|
||||
* @returns Current conversation ID or null
|
||||
*/
|
||||
getCurrentConversationId(): string | null {
|
||||
return this.conversationId
|
||||
}
|
||||
|
||||
/**
|
||||
* Set conversation ID for continuing existing conversations
|
||||
* @param conversationId Conversation ID to set
|
||||
*/
|
||||
setConversationId(conversationId: string): void {
|
||||
this.conversationId = conversationId
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset conversation ID to start a new conversation
|
||||
*/
|
||||
resetConversation(): void {
|
||||
this.conversationId = null
|
||||
this.currentTaskId = null
|
||||
}
|
||||
}
|
||||
@@ -251,6 +251,8 @@ export class CacheService {
|
||||
basetenApiKey,
|
||||
huggingFaceApiKey,
|
||||
huaweiCloudMaasApiKey,
|
||||
difyApiKey,
|
||||
difyBaseUrl,
|
||||
vercelAiGatewayApiKey,
|
||||
zaiApiKey,
|
||||
requestTimeoutMs,
|
||||
@@ -419,6 +421,7 @@ export class CacheService {
|
||||
sapAiCoreTokenUrl,
|
||||
sapAiResourceGroup,
|
||||
claudeCodePath,
|
||||
difyBaseUrl,
|
||||
qwenCodeOauthPath,
|
||||
})
|
||||
|
||||
@@ -455,6 +458,7 @@ export class CacheService {
|
||||
basetenApiKey,
|
||||
huggingFaceApiKey,
|
||||
huaweiCloudMaasApiKey,
|
||||
difyApiKey,
|
||||
vercelAiGatewayApiKey,
|
||||
zaiApiKey,
|
||||
})
|
||||
@@ -682,6 +686,8 @@ export class CacheService {
|
||||
qwenCodeOauthPath,
|
||||
huggingFaceApiKey,
|
||||
huaweiCloudMaasApiKey,
|
||||
difyApiKey,
|
||||
difyBaseUrl,
|
||||
vercelAiGatewayApiKey,
|
||||
zaiApiKey,
|
||||
requestTimeoutMs,
|
||||
@@ -882,6 +888,7 @@ export class CacheService {
|
||||
sapAiCoreTokenUrl,
|
||||
sapAiResourceGroup,
|
||||
claudeCodePath,
|
||||
difyBaseUrl,
|
||||
qwenCodeOauthPath,
|
||||
} satisfies GlobalState
|
||||
|
||||
@@ -922,6 +929,7 @@ export class CacheService {
|
||||
authNonce,
|
||||
huggingFaceApiKey,
|
||||
huaweiCloudMaasApiKey,
|
||||
difyApiKey,
|
||||
vercelAiGatewayApiKey,
|
||||
zaiApiKey,
|
||||
} satisfies Secrets
|
||||
@@ -977,6 +985,7 @@ export class CacheService {
|
||||
sapAiCoreClientSecret: this.secretsCache["sapAiCoreClientSecret"],
|
||||
huggingFaceApiKey: this.secretsCache["huggingFaceApiKey"],
|
||||
huaweiCloudMaasApiKey: this.secretsCache["huaweiCloudMaasApiKey"],
|
||||
difyApiKey: this.secretsCache["difyApiKey"],
|
||||
vercelAiGatewayApiKey: this.secretsCache["vercelAiGatewayApiKey"],
|
||||
zaiApiKey: this.secretsCache["zaiApiKey"],
|
||||
|
||||
@@ -1016,6 +1025,7 @@ export class CacheService {
|
||||
sapAiResourceGroup: this.globalStateCache["sapAiResourceGroup"],
|
||||
claudeCodePath: this.globalStateCache["claudeCodePath"],
|
||||
qwenCodeOauthPath: this.globalStateCache["qwenCodeOauthPath"],
|
||||
difyBaseUrl: this.globalStateCache["difyBaseUrl"],
|
||||
|
||||
// Plan mode configurations
|
||||
planModeApiProvider: this.globalStateCache["planModeApiProvider"],
|
||||
|
||||
@@ -46,6 +46,7 @@ export type SecretKey =
|
||||
| "basetenApiKey"
|
||||
| "vercelAiGatewayApiKey"
|
||||
| "zaiApiKey"
|
||||
| "difyApiKey"
|
||||
|
||||
export type GlobalStateKey =
|
||||
| "awsRegion"
|
||||
@@ -103,6 +104,7 @@ export type GlobalStateKey =
|
||||
| "sapAiCoreBaseUrl"
|
||||
| "sapAiResourceGroup"
|
||||
| "claudeCodePath"
|
||||
| "difyBaseUrl"
|
||||
| "qwenCodeOauthPath"
|
||||
| "strictPlanModeEnabled"
|
||||
| "useAutoCondense"
|
||||
@@ -243,6 +245,7 @@ export interface GlobalState {
|
||||
focusChainSettings: FocusChainSettings
|
||||
focusChainFeatureFlagEnabled: boolean
|
||||
customPrompt: "compact" | undefined
|
||||
difyBaseUrl: string | undefined
|
||||
|
||||
// Plan mode configurations
|
||||
planModeApiProvider: ApiProvider
|
||||
@@ -343,6 +346,7 @@ export interface Secrets {
|
||||
huaweiCloudMaasApiKey: string | undefined
|
||||
basetenApiKey: string | undefined
|
||||
vercelAiGatewayApiKey: string | undefined
|
||||
difyApiKey: string | undefined
|
||||
}
|
||||
|
||||
export interface LocalState {
|
||||
|
||||
@@ -545,6 +545,7 @@ export async function migrateWelcomeViewCompleted(context: vscode.ExtensionConte
|
||||
config.xaiApiKey,
|
||||
config.sambanovaApiKey,
|
||||
config.sapAiCoreClientId,
|
||||
config.difyApiKey,
|
||||
].some((key) => key !== undefined)
|
||||
: false
|
||||
|
||||
|
||||
@@ -68,6 +68,7 @@ export async function readStateFromDisk(context: ExtensionContext) {
|
||||
const sapAiCoreTokenUrl = context.globalState.get("sapAiCoreTokenUrl") as string | undefined
|
||||
const sapAiResourceGroup = context.globalState.get("sapAiResourceGroup") as string | undefined
|
||||
const claudeCodePath = context.globalState.get("claudeCodePath") as string | undefined
|
||||
const difyBaseUrl = context.globalState.get("difyBaseUrl") as string | undefined
|
||||
const openaiReasoningEffort = context.globalState.get("openaiReasoningEffort") as OpenaiReasoningEffort | undefined
|
||||
const preferredLanguage = context.globalState.get("preferredLanguage") as string | undefined
|
||||
|
||||
@@ -106,6 +107,7 @@ export async function readStateFromDisk(context: ExtensionContext) {
|
||||
zaiApiKey,
|
||||
ollamaApiKey,
|
||||
vercelAiGatewayApiKey,
|
||||
difyApiKey,
|
||||
] = await Promise.all([
|
||||
context.secrets.get("apiKey") as Promise<string | undefined>,
|
||||
context.secrets.get("openRouterApiKey") as Promise<string | undefined>,
|
||||
@@ -140,6 +142,7 @@ export async function readStateFromDisk(context: ExtensionContext) {
|
||||
context.secrets.get("zaiApiKey") as Promise<string | undefined>,
|
||||
context.secrets.get("ollamaApiKey") as Promise<string | undefined>,
|
||||
context.secrets.get("vercelAiGatewayApiKey") as Promise<string | undefined>,
|
||||
context.secrets.get("difyApiKey") as Promise<string | undefined>,
|
||||
])
|
||||
|
||||
const localClineRulesToggles = context.workspaceState.get("localClineRulesToggles") as ClineRulesToggles | undefined
|
||||
@@ -321,6 +324,8 @@ export async function readStateFromDisk(context: ExtensionContext) {
|
||||
zaiApiKey,
|
||||
ollamaApiKey,
|
||||
vercelAiGatewayApiKey,
|
||||
difyApiKey,
|
||||
difyBaseUrl,
|
||||
// Plan mode configurations
|
||||
planModeApiProvider: planModeApiProvider || apiProvider,
|
||||
planModeApiModelId,
|
||||
@@ -459,6 +464,7 @@ export async function resetGlobalState(controller: Controller) {
|
||||
"huaweiCloudMaasApiKey",
|
||||
"vercelAiGatewayApiKey",
|
||||
"zaiApiKey",
|
||||
"difyApiKey",
|
||||
]
|
||||
await Promise.all(secretKeys.map((key) => context.secrets.delete(key)))
|
||||
await controller.cacheService.reInitialize()
|
||||
|
||||
@@ -0,0 +1,271 @@
|
||||
import { DifyHandler } from "../../core/api/providers/dify"
|
||||
|
||||
/**
|
||||
* Dify Integration Utilities
|
||||
*
|
||||
* This module provides helper functions to integrate Dify's additional APIs
|
||||
* with Cline's existing systems like file handling, conversation management,
|
||||
* and feedback collection.
|
||||
*/
|
||||
|
||||
export interface DifyIntegrationOptions {
|
||||
difyHandler: DifyHandler
|
||||
onConversationChange?: (conversationId: string) => void
|
||||
onFileUploaded?: (fileId: string, filename: string) => void
|
||||
onFeedbackSubmitted?: (messageId: string, rating: "like" | "dislike") => void
|
||||
}
|
||||
|
||||
export class DifyIntegration {
|
||||
private handler: DifyHandler
|
||||
private onConversationChange?: (conversationId: string) => void
|
||||
private onFileUploaded?: (fileId: string, filename: string) => void
|
||||
private onFeedbackSubmitted?: (messageId: string, rating: "like" | "dislike") => void
|
||||
|
||||
constructor(options: DifyIntegrationOptions) {
|
||||
this.handler = options.difyHandler
|
||||
this.onConversationChange = options.onConversationChange
|
||||
this.onFileUploaded = options.onFileUploaded
|
||||
this.onFeedbackSubmitted = options.onFeedbackSubmitted
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload multiple files and return their IDs for use in conversations
|
||||
* @param files Array of file data with name and content
|
||||
* @param user User identifier (defaults to "cline-user")
|
||||
* @returns Array of uploaded file IDs
|
||||
*/
|
||||
async uploadFiles(files: Array<{ name: string; content: Buffer }>, user?: string): Promise<string[]> {
|
||||
const uploadedFileIds: string[] = []
|
||||
|
||||
for (const file of files) {
|
||||
try {
|
||||
const response = await this.handler.uploadFile(file.content, file.name, user)
|
||||
uploadedFileIds.push(response.id)
|
||||
|
||||
// Notify about successful upload
|
||||
if (this.onFileUploaded) {
|
||||
this.onFileUploaded(response.id, file.name)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Failed to upload file ${file.name}:`, error)
|
||||
throw new Error(`File upload failed for ${file.name}: ${error instanceof Error ? error.message : String(error)}`)
|
||||
}
|
||||
}
|
||||
|
||||
return uploadedFileIds
|
||||
}
|
||||
|
||||
/**
|
||||
* Enhanced conversation management with callbacks
|
||||
* @param conversationId Conversation ID to switch to
|
||||
*/
|
||||
async switchToConversation(conversationId: string): Promise<void> {
|
||||
this.handler.setConversationId(conversationId)
|
||||
|
||||
if (this.onConversationChange) {
|
||||
this.onConversationChange(conversationId)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Start a new conversation and notify listeners
|
||||
*/
|
||||
async startNewConversation(): Promise<void> {
|
||||
this.handler.resetConversation()
|
||||
|
||||
if (this.onConversationChange) {
|
||||
this.onConversationChange("new")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get conversation history with error handling and formatting
|
||||
* @param conversationId Conversation ID (uses current if not provided)
|
||||
* @param user User identifier
|
||||
* @param limit Number of messages to fetch
|
||||
* @returns Formatted conversation history
|
||||
*/
|
||||
async getFormattedConversationHistory(
|
||||
conversationId?: string,
|
||||
user?: string,
|
||||
limit: number = 20,
|
||||
): Promise<Array<{ role: "user" | "assistant"; content: string; timestamp: number; id: string }>> {
|
||||
const currentConversationId = conversationId || this.handler.getCurrentConversationId()
|
||||
|
||||
if (!currentConversationId) {
|
||||
throw new Error("No conversation ID available")
|
||||
}
|
||||
|
||||
try {
|
||||
const history = await this.handler.getConversationHistory(currentConversationId, user, undefined, limit)
|
||||
|
||||
return history.data
|
||||
.map((message) => ({
|
||||
role: "user" as const, // Dify messages are typically user queries
|
||||
content: message.query || message.answer || "",
|
||||
timestamp: message.created_at,
|
||||
id: message.id,
|
||||
}))
|
||||
.reverse() // Reverse to get chronological order
|
||||
} catch (error) {
|
||||
console.error("Failed to get conversation history:", error)
|
||||
throw new Error(`Failed to retrieve conversation history: ${error instanceof Error ? error.message : String(error)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Submit feedback with enhanced error handling
|
||||
* @param messageId Message ID to provide feedback for
|
||||
* @param rating Rating: "like" or "dislike"
|
||||
* @param content Optional feedback content
|
||||
* @param user User identifier
|
||||
*/
|
||||
async submitFeedback(messageId: string, rating: "like" | "dislike", content?: string, user?: string): Promise<void> {
|
||||
try {
|
||||
await this.handler.submitMessageFeedback(messageId, rating, content, user)
|
||||
|
||||
if (this.onFeedbackSubmitted) {
|
||||
this.onFeedbackSubmitted(messageId, rating)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to submit feedback:", error)
|
||||
throw new Error(`Failed to submit feedback: ${error instanceof Error ? error.message : String(error)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all conversations for the user with enhanced formatting
|
||||
* @param user User identifier
|
||||
* @param limit Number of conversations to fetch
|
||||
* @returns Formatted conversation list
|
||||
*/
|
||||
async getConversationList(
|
||||
user?: string,
|
||||
limit: number = 20,
|
||||
): Promise<
|
||||
Array<{
|
||||
id: string
|
||||
name: string
|
||||
lastUpdated: number
|
||||
status: string
|
||||
messageCount?: number
|
||||
}>
|
||||
> {
|
||||
try {
|
||||
const conversations = await this.handler.getConversations(user, undefined, limit)
|
||||
|
||||
return conversations.data.map((conv) => ({
|
||||
id: conv.id,
|
||||
name: conv.name || "Untitled Conversation",
|
||||
lastUpdated: conv.updated_at,
|
||||
status: conv.status,
|
||||
}))
|
||||
} catch (error) {
|
||||
console.error("Failed to get conversation list:", error)
|
||||
throw new Error(`Failed to retrieve conversations: ${error instanceof Error ? error.message : String(error)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Auto-rename conversation based on content
|
||||
* @param conversationId Conversation ID to rename
|
||||
* @param user User identifier
|
||||
* @returns New conversation name
|
||||
*/
|
||||
async autoRenameConversation(conversationId?: string, user?: string): Promise<string> {
|
||||
const targetConversationId = conversationId || this.handler.getCurrentConversationId()
|
||||
|
||||
if (!targetConversationId) {
|
||||
throw new Error("No conversation ID available for renaming")
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await this.handler.renameConversation(targetConversationId, user, undefined, true)
|
||||
return result.name
|
||||
} catch (error) {
|
||||
console.error("Failed to auto-rename conversation:", error)
|
||||
throw new Error(`Failed to rename conversation: ${error instanceof Error ? error.message : String(error)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete conversation with confirmation
|
||||
* @param conversationId Conversation ID to delete
|
||||
* @param user User identifier
|
||||
*/
|
||||
async deleteConversation(conversationId: string, user?: string): Promise<void> {
|
||||
try {
|
||||
await this.handler.deleteConversation(conversationId, user)
|
||||
} catch (error) {
|
||||
console.error("Failed to delete conversation:", error)
|
||||
throw new Error(`Failed to delete conversation: ${error instanceof Error ? error.message : String(error)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop current generation if task ID is available
|
||||
* @param taskId Task ID to stop
|
||||
* @param user User identifier
|
||||
*/
|
||||
async stopCurrentGeneration(taskId: string, user?: string): Promise<void> {
|
||||
try {
|
||||
await this.handler.stopGeneration(taskId, user)
|
||||
} catch (error) {
|
||||
console.error("Failed to stop generation:", error)
|
||||
throw new Error(`Failed to stop generation: ${error instanceof Error ? error.message : String(error)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the underlying Dify handler for direct access
|
||||
* @returns DifyHandler instance
|
||||
*/
|
||||
getHandler(): DifyHandler {
|
||||
return this.handler
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to create a Dify integration instance
|
||||
* @param handler DifyHandler instance
|
||||
* @param callbacks Optional callback functions
|
||||
* @returns DifyIntegration instance
|
||||
*/
|
||||
export function createDifyIntegration(
|
||||
handler: DifyHandler,
|
||||
callbacks?: {
|
||||
onConversationChange?: (conversationId: string) => void
|
||||
onFileUploaded?: (fileId: string, filename: string) => void
|
||||
onFeedbackSubmitted?: (messageId: string, rating: "like" | "dislike") => void
|
||||
},
|
||||
): DifyIntegration {
|
||||
return new DifyIntegration({
|
||||
difyHandler: handler,
|
||||
...callbacks,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility function to convert Cline file objects to Dify upload format
|
||||
* @param files Array of file paths or file objects from Cline
|
||||
* @returns Promise with array of file data ready for upload
|
||||
*/
|
||||
export async function prepareClineFilesForDify(files: string[]): Promise<Array<{ name: string; content: Buffer }>> {
|
||||
const fs = await import("fs")
|
||||
const path = await import("path")
|
||||
|
||||
const fileData: Array<{ name: string; content: Buffer }> = []
|
||||
|
||||
for (const filePath of files) {
|
||||
try {
|
||||
const content = fs.readFileSync(filePath)
|
||||
const name = path.basename(filePath)
|
||||
fileData.push({ name, content })
|
||||
} catch (error) {
|
||||
console.error(`Failed to read file ${filePath}:`, error)
|
||||
throw new Error(`Failed to read file ${filePath}: ${error instanceof Error ? error.message : String(error)}`)
|
||||
}
|
||||
}
|
||||
|
||||
return fileData
|
||||
}
|
||||
@@ -32,6 +32,7 @@ export type ApiProvider =
|
||||
| "groq"
|
||||
| "huggingface"
|
||||
| "huawei-cloud-maas"
|
||||
| "dify"
|
||||
| "baseten"
|
||||
| "vercel-ai-gateway"
|
||||
| "zai"
|
||||
@@ -105,6 +106,8 @@ export interface ApiHandlerOptions {
|
||||
sapAiCoreTokenUrl?: string
|
||||
sapAiCoreBaseUrl?: string
|
||||
huaweiCloudMaasApiKey?: string
|
||||
difyApiKey?: string
|
||||
difyBaseUrl?: string
|
||||
zaiApiKey?: string
|
||||
zaiApiLine?: string
|
||||
onRetryAttempt?: (attempt: number, maxRetries: number, delay: number, error: any) => void
|
||||
@@ -3157,6 +3160,8 @@ export type MoonshotModelId = keyof typeof moonshotModels
|
||||
export const moonshotDefaultModelId = "kimi-k2-0711-preview" satisfies MoonshotModelId
|
||||
|
||||
// Huawei Cloud MaaS
|
||||
// Dify.ai - No model selection needed, models are configured in Dify workflows
|
||||
|
||||
export type HuaweiCloudMaasModelId = keyof typeof huaweiCloudMaasModels
|
||||
export const huaweiCloudMaasDefaultModelId: HuaweiCloudMaasModelId = "DeepSeek-V3"
|
||||
export const huaweiCloudMaasModels = {
|
||||
|
||||
@@ -254,6 +254,8 @@ function convertApiProviderToProto(provider: string | undefined): ProtoApiProvid
|
||||
return ProtoApiProvider.VERCEL_AI_GATEWAY
|
||||
case "zai":
|
||||
return ProtoApiProvider.ZAI
|
||||
case "dify":
|
||||
return ProtoApiProvider.DIFY
|
||||
default:
|
||||
return ProtoApiProvider.ANTHROPIC
|
||||
}
|
||||
@@ -330,6 +332,8 @@ function convertProtoToApiProvider(provider: ProtoApiProvider): ApiProvider {
|
||||
return "vercel-ai-gateway"
|
||||
case ProtoApiProvider.ZAI:
|
||||
return "zai"
|
||||
case ProtoApiProvider.DIFY:
|
||||
return "dify"
|
||||
default:
|
||||
return "anthropic"
|
||||
}
|
||||
@@ -407,6 +411,8 @@ export function convertApiConfigurationToProto(config: ApiConfiguration): ProtoA
|
||||
huaweiCloudMaasApiKey: config.huaweiCloudMaasApiKey,
|
||||
zaiApiLine: config.zaiApiLine,
|
||||
zaiApiKey: config.zaiApiKey,
|
||||
difyApiKey: config.difyApiKey,
|
||||
difyBaseUrl: config.difyBaseUrl,
|
||||
|
||||
// Plan mode configurations
|
||||
planModeApiProvider: config.planModeApiProvider ? convertApiProviderToProto(config.planModeApiProvider) : undefined,
|
||||
@@ -549,6 +555,8 @@ export function convertProtoToApiConfiguration(protoConfig: ProtoApiConfiguratio
|
||||
huaweiCloudMaasApiKey: protoConfig.huaweiCloudMaasApiKey,
|
||||
zaiApiLine: protoConfig.zaiApiLine,
|
||||
zaiApiKey: protoConfig.zaiApiKey,
|
||||
difyApiKey: protoConfig.difyApiKey,
|
||||
difyBaseUrl: protoConfig.difyBaseUrl,
|
||||
|
||||
// Plan mode configurations
|
||||
planModeApiProvider:
|
||||
|
||||
@@ -70,6 +70,8 @@ export function convertApiConfigurationToProtoApiConfiguration(config: ApiConfig
|
||||
sapAiCoreTokenUrl: config.sapAiCoreTokenUrl,
|
||||
sapAiCoreBaseUrl: config.sapAiCoreBaseUrl,
|
||||
vercelAiGatewayApiKey: config.vercelAiGatewayApiKey,
|
||||
difyBaseUrl: config.difyBaseUrl,
|
||||
difyApiKey: config.difyApiKey,
|
||||
|
||||
// Plan mode configurations
|
||||
planModeApiProvider: config.planModeApiProvider,
|
||||
@@ -208,6 +210,8 @@ export function convertProtoApiConfigurationToApiConfiguration(protoConfig: Prot
|
||||
sapAiCoreTokenUrl: protoConfig.sapAiCoreTokenUrl,
|
||||
sapAiCoreBaseUrl: protoConfig.sapAiCoreBaseUrl,
|
||||
vercelAiGatewayApiKey: protoConfig.vercelAiGatewayApiKey,
|
||||
difyApiKey: protoConfig.difyApiKey,
|
||||
difyBaseUrl: protoConfig.difyBaseUrl,
|
||||
|
||||
// Plan mode configurations
|
||||
planModeApiProvider: protoConfig.planModeApiProvider as ApiProvider,
|
||||
|
||||
@@ -16,6 +16,7 @@ import { CerebrasProvider } from "./providers/CerebrasProvider"
|
||||
import { ClaudeCodeProvider } from "./providers/ClaudeCodeProvider"
|
||||
import { ClineProvider } from "./providers/ClineProvider"
|
||||
import { DeepSeekProvider } from "./providers/DeepSeekProvider"
|
||||
import { DifyProvider } from "./providers/DifyProvider"
|
||||
import { DoubaoProvider } from "./providers/DoubaoProvider"
|
||||
import { FireworksProvider } from "./providers/FireworksProvider"
|
||||
import { GeminiProvider } from "./providers/GeminiProvider"
|
||||
@@ -174,6 +175,7 @@ const ApiOptions = ({ showModelOptions, apiErrorMessage, modelIdErrorMessage, is
|
||||
<VSCodeOption value="xai">xAI</VSCodeOption>
|
||||
<VSCodeOption value="sambanova">SambaNova</VSCodeOption>
|
||||
<VSCodeOption value="huawei-cloud-maas">Huawei Cloud MaaS</VSCodeOption>
|
||||
<VSCodeOption value="dify">Dify.ai</VSCodeOption>
|
||||
</VSCodeDropdown>
|
||||
</DropdownContainer>
|
||||
|
||||
@@ -305,6 +307,10 @@ const ApiOptions = ({ showModelOptions, apiErrorMessage, modelIdErrorMessage, is
|
||||
<HuaweiCloudMaasProvider currentMode={currentMode} isPopup={isPopup} showModelOptions={showModelOptions} />
|
||||
)}
|
||||
|
||||
{apiConfiguration && selectedProvider === "dify" && (
|
||||
<DifyProvider currentMode={currentMode} isPopup={isPopup} showModelOptions={showModelOptions} />
|
||||
)}
|
||||
|
||||
{apiConfiguration && selectedProvider === "zai" && (
|
||||
<ZAiProvider currentMode={currentMode} isPopup={isPopup} showModelOptions={showModelOptions} />
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { Mode } from "@shared/storage/types"
|
||||
import { VSCodeTextField } from "@vscode/webview-ui-toolkit/react"
|
||||
import { useExtensionState } from "@/context/ExtensionStateContext"
|
||||
import { ApiKeyField } from "../common/ApiKeyField"
|
||||
import { DebouncedTextField } from "../common/DebouncedTextField"
|
||||
import { ModelInfoView } from "../common/ModelInfoView"
|
||||
import { normalizeApiConfiguration } from "../utils/providerUtils"
|
||||
import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers"
|
||||
import { useDebouncedInput } from "../utils/useDebouncedInput"
|
||||
|
||||
interface DifyProviderProps {
|
||||
showModelOptions: boolean
|
||||
isPopup?: boolean
|
||||
currentMode: Mode
|
||||
}
|
||||
|
||||
export const DifyProvider = ({ showModelOptions, isPopup, currentMode }: DifyProviderProps) => {
|
||||
const { apiConfiguration } = useExtensionState()
|
||||
const { handleFieldChange } = useApiConfigurationHandlers()
|
||||
|
||||
// Use debounced input for proper state management
|
||||
const [baseUrlValue, setBaseUrlValue] = useDebouncedInput(apiConfiguration?.difyBaseUrl || "", (value) =>
|
||||
handleFieldChange("difyBaseUrl", value),
|
||||
)
|
||||
|
||||
const [apiKeyValue, setApiKeyValue] = useDebouncedInput(apiConfiguration?.difyApiKey || "", (value) =>
|
||||
handleFieldChange("difyApiKey", value),
|
||||
)
|
||||
|
||||
// Get the normalized configuration
|
||||
const { selectedModelId, selectedModelInfo } = normalizeApiConfiguration(apiConfiguration, currentMode)
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
|
||||
<DebouncedTextField
|
||||
initialValue={apiConfiguration?.difyBaseUrl || ""}
|
||||
onChange={(value) => {
|
||||
handleFieldChange("difyBaseUrl", value)
|
||||
}}
|
||||
placeholder={"Enter base URL..."}
|
||||
style={{ width: "100%", marginBottom: 10 }}
|
||||
type="url">
|
||||
<span style={{ fontWeight: 500 }}>Base URL</span>
|
||||
</DebouncedTextField>
|
||||
|
||||
<ApiKeyField
|
||||
initialValue={apiConfiguration?.difyApiKey || ""}
|
||||
onChange={(value) => {
|
||||
handleFieldChange("difyApiKey", value)
|
||||
}}
|
||||
providerName="Dify"
|
||||
/>
|
||||
|
||||
<div style={{ fontSize: "12px", color: "var(--vscode-descriptionForeground)", marginTop: "5px" }}>
|
||||
<p>
|
||||
Dify is a platform that provides access to various AI models through a unified API. Configure your Dify
|
||||
instance URL and API key to get started.
|
||||
</p>
|
||||
<p style={{ marginTop: "8px" }}>
|
||||
<strong>Note:</strong> The model selection is handled within your Dify application configuration.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{showModelOptions && (
|
||||
<ModelInfoView isPopup={isPopup} modelInfo={selectedModelInfo} selectedModelId={selectedModelId} />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -301,6 +301,20 @@ export function normalizeApiConfiguration(
|
||||
selectedModelId: huaweiCloudMaasModelId || huaweiCloudMaasDefaultModelId,
|
||||
selectedModelInfo: huaweiCloudMaasModelInfo || huaweiCloudMaasModels[huaweiCloudMaasDefaultModelId],
|
||||
}
|
||||
case "dify":
|
||||
return {
|
||||
selectedProvider: provider,
|
||||
selectedModelId: "dify-workflow",
|
||||
selectedModelInfo: {
|
||||
maxTokens: 8192,
|
||||
contextWindow: 128000,
|
||||
supportsImages: true,
|
||||
supportsPromptCache: false,
|
||||
inputPrice: 0,
|
||||
outputPrice: 0,
|
||||
description: "Dify workflow - model selection is configured in your Dify application",
|
||||
},
|
||||
}
|
||||
case "vercel-ai-gateway":
|
||||
const vercelAiGatewayModelId =
|
||||
currentMode === "plan"
|
||||
@@ -571,6 +585,12 @@ export async function syncModeConfigurations(
|
||||
updates.planModeHuaweiCloudMaasModelInfo = sourceFields.huaweiCloudMaasModelInfo
|
||||
updates.actModeHuaweiCloudMaasModelInfo = sourceFields.huaweiCloudMaasModelInfo
|
||||
break
|
||||
|
||||
case "dify":
|
||||
// Dify doesn't have mode-specific model configurations
|
||||
// The model is configured in the Dify application itself
|
||||
break
|
||||
|
||||
case "vercel-ai-gateway":
|
||||
updates.planModeVercelAiGatewayModelId = sourceFields.vercelAiGatewayModelId
|
||||
updates.actModeVercelAiGatewayModelId = sourceFields.vercelAiGatewayModelId
|
||||
|
||||
@@ -149,6 +149,14 @@ export function validateApiConfiguration(currentMode: Mode, apiConfiguration?: A
|
||||
return "You must provide a valid API key or choose a different provider."
|
||||
}
|
||||
break
|
||||
case "dify":
|
||||
if (!apiConfiguration.difyBaseUrl) {
|
||||
return "You must provide a valid Base URL or choose a different provider."
|
||||
}
|
||||
if (!apiConfiguration.difyApiKey) {
|
||||
return "You must provide a valid API key or choose a different provider."
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
|
||||
Reference in new issue
Block a user