-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathqwen_simple.rs
More file actions
412 lines (358 loc) · 13.3 KB
/
qwen_simple.rs
File metadata and controls
412 lines (358 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
// ABOUTME: Provides a minimal client for invoking a local Qwen model via an Ollama-compatible API.
// ABOUTME: Supports availability checks and request/response shaping for code analysis prompts.
use crate::llm_provider::*;
use async_trait::async_trait;
use codegraph_core::{CodeGraphError, Result};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::sync::OnceLock;
use std::time::{Duration, Instant};
use tokio::time::timeout;
use tracing::{debug, info};
/// Simple Qwen2.5-Coder client for CodeGraph MCP integration
#[derive(Debug, Clone)]
pub struct QwenConfig {
pub model_name: String,
pub base_url: String,
pub context_window: usize,
pub max_tokens: usize,
pub temperature: f32,
pub timeout: Duration,
}
impl Default for QwenConfig {
fn default() -> Self {
Self {
model_name: "qwen2.5-coder-14b-128k".to_string(),
base_url: "http://localhost:11434".to_string(),
context_window: 128000,
max_tokens: 8192,
temperature: 0.1,
timeout: Duration::from_secs(90),
}
}
}
#[derive(Debug, Serialize)]
struct SimpleRequest {
model: String,
prompt: String,
stream: bool,
options: SimpleOptions,
}
#[derive(Debug, Serialize)]
struct SimpleOptions {
temperature: f32,
num_predict: usize,
num_ctx: usize,
}
#[derive(Debug, Deserialize)]
struct SimpleResponse {
response: String,
#[serde(default)]
eval_count: Option<usize>,
#[serde(default)]
prompt_eval_count: Option<usize>,
}
#[derive(Debug, Clone)]
pub struct QwenResult {
pub text: String,
pub model_used: String,
pub processing_time: Duration,
pub context_tokens: usize,
pub completion_tokens: usize,
pub confidence_score: f32,
}
pub struct QwenClient {
client: OnceLock<Client>,
config: QwenConfig,
}
impl QwenClient {
pub fn new(config: QwenConfig) -> Self {
Self {
client: OnceLock::new(),
config,
}
}
fn client(&self) -> Result<&Client> {
if let Some(client) = self.client.get() {
return Ok(client);
}
let built = std::panic::catch_unwind(Client::new)
.map_err(|_| CodeGraphError::Network("Failed to initialize HTTP client".to_string()))?;
let _ = self.client.set(built);
Ok(self.client.get().expect("client should be initialized"))
}
/// Generate analysis using Qwen2.5-Coder with comprehensive context
pub async fn generate_analysis(
&self,
prompt: &str,
system_prompt: Option<&str>,
) -> Result<QwenResult> {
let start_time = Instant::now();
// Build full prompt with system context if provided
let full_prompt = if let Some(sys_prompt) = system_prompt {
format!("{}\n\nUser: {}\n\nAssistant:", sys_prompt, prompt)
} else {
format!("You are Qwen2.5-Coder, a state-of-the-art AI specialized in comprehensive code analysis. Provide detailed, structured analysis.\n\nUser: {}\n\nAssistant:", prompt)
};
let request = SimpleRequest {
model: self.config.model_name.clone(),
prompt: full_prompt,
stream: false,
options: SimpleOptions {
temperature: self.config.temperature,
num_predict: self.config.max_tokens,
num_ctx: self.config.context_window,
},
};
debug!(
"Sending request to Qwen2.5-Coder: {} context window",
self.config.context_window
);
let response = timeout(
self.config.timeout,
self.client()?
.post(format!("{}/api/generate", self.config.base_url))
.json(&request)
.send(),
)
.await
.map_err(|_| {
CodeGraphError::Timeout(format!(
"Qwen request timeout after {:?}",
self.config.timeout
))
})?
.map_err(|e| CodeGraphError::Network(format!("Qwen request failed: {}", e)))?;
if !response.status().is_success() {
let error_text = response
.text()
.await
.unwrap_or_else(|_| "Unknown error".to_string());
return Err(CodeGraphError::External(format!(
"Qwen API error: {}",
error_text
)));
}
let response_data: SimpleResponse = response
.json()
.await
.map_err(|e| CodeGraphError::Parse(format!("Failed to parse Qwen response: {}", e)))?;
let processing_time = start_time.elapsed();
let confidence_score = self.calculate_confidence(&response_data.response);
let result = QwenResult {
text: response_data.response,
model_used: self.config.model_name.clone(),
processing_time,
context_tokens: response_data.prompt_eval_count.unwrap_or(0),
completion_tokens: response_data.eval_count.unwrap_or(0),
confidence_score,
};
info!(
"Qwen analysis completed: {}ms, context: {} tokens, completion: {} tokens",
processing_time.as_millis(),
result.context_tokens,
result.completion_tokens
);
Ok(result)
}
/// Check if Qwen2.5-Coder model is available
pub async fn check_availability(&self) -> Result<bool> {
debug!(
"Checking Qwen2.5-Coder availability at {}",
self.config.base_url
);
let response = timeout(
Duration::from_secs(5),
self.client()?
.get(format!("{}/api/tags", self.config.base_url))
.send(),
)
.await
.map_err(|_| CodeGraphError::Timeout("Qwen availability check timeout".to_string()))?
.map_err(|e| CodeGraphError::Network(format!("Qwen availability check failed: {}", e)))?;
if !response.status().is_success() {
return Ok(false);
}
let models: serde_json::Value = response
.json()
.await
.map_err(|_| CodeGraphError::Parse("Failed to parse models response".to_string()))?;
let has_qwen = models["models"]
.as_array()
.map(|models| {
models.iter().any(|model| {
model["name"]
.as_str()
.map(|name| name.contains("qwen") && name.contains("coder"))
.unwrap_or(false)
})
})
.unwrap_or(false);
info!("Qwen2.5-Coder availability: {}", has_qwen);
Ok(has_qwen)
}
fn calculate_confidence(&self, response: &str) -> f32 {
let mut confidence: f32 = 0.5;
// Structured response indicates higher confidence
if response.contains("1.") && response.contains("2.") {
confidence += 0.2;
}
// Code examples indicate thorough analysis
if response.contains("```") {
confidence += 0.1;
}
// Detailed responses indicate comprehensive analysis
if response.len() > 1000 {
confidence += 0.1;
}
// Technical terminology indicates code understanding
if response.contains("function")
|| response.contains("class")
|| response.contains("module")
{
confidence += 0.1;
}
confidence.min(0.95) // Cap at 95%
}
}
// LLMProvider trait implementation for QwenClient
#[async_trait]
impl LLMProvider for QwenClient {
async fn generate_chat(
&self,
messages: &[Message],
config: &GenerationConfig,
) -> LLMResult<LLMResponse> {
// Build prompt from messages
let prompt = messages
.iter()
.map(|m| match m.role {
MessageRole::System => format!("System: {}", m.content),
MessageRole::User => format!("User: {}", m.content),
MessageRole::Assistant => format!("Assistant: {}", m.content),
})
.collect::<Vec<_>>()
.join("\n\n");
let prompt = format!("{}\n\nAssistant:", prompt);
let request = SimpleRequest {
model: self.config.model_name.clone(),
prompt,
stream: false,
options: SimpleOptions {
temperature: config.temperature,
num_predict: config.max_tokens.unwrap_or(self.config.max_tokens),
num_ctx: self.config.context_window,
},
};
let response = timeout(
self.config.timeout,
self.client()?
.post(format!("{}/api/generate", self.config.base_url))
.json(&request)
.send(),
)
.await
.map_err(|_| anyhow::anyhow!("Qwen request timeout"))?
.map_err(|e| anyhow::anyhow!("Qwen request failed: {}", e))?;
if !response.status().is_success() {
let error_text = response
.text()
.await
.unwrap_or_else(|_| "Unknown error".to_string());
return Err(anyhow::anyhow!("Qwen API error: {}", error_text));
}
let response_data: SimpleResponse = response
.json()
.await
.map_err(|e| anyhow::anyhow!("Failed to parse Qwen response: {}", e))?;
let content = response_data.response.clone();
Ok(LLMResponse {
answer: content.clone(),
content,
total_tokens: Some(
response_data.prompt_eval_count.unwrap_or(0)
+ response_data.eval_count.unwrap_or(0),
),
prompt_tokens: response_data.prompt_eval_count,
completion_tokens: response_data.eval_count,
finish_reason: Some("stop".to_string()),
model: self.config.model_name.clone(),
tool_calls: None,
})
}
async fn is_available(&self) -> bool {
self.check_availability().await.unwrap_or(false)
}
fn provider_name(&self) -> &str {
"qwen"
}
fn model_name(&self) -> &str {
&self.config.model_name
}
fn characteristics(&self) -> ProviderCharacteristics {
ProviderCharacteristics {
max_tokens: self.config.context_window,
avg_latency_ms: 2000,
rpm_limit: None,
tpm_limit: None,
supports_streaming: true,
supports_functions: false,
}
}
}
#[async_trait]
impl CodeIntelligenceProvider for QwenClient {
async fn analyze_semantic_context(&self, query: &str, context: &str) -> LLMResult<String> {
let prompt = format!(
"Analyze this codebase context for semantic understanding:\n\n\
SEARCH QUERY: {}\n\n\
CODEBASE CONTEXT:\n{}\n\n\
Provide structured semantic analysis:\n\
1. SEMANTIC_MATCHES: What code semantically matches the query and why\n\
2. ARCHITECTURAL_CONTEXT: How this functionality fits in the system\n\
3. USAGE_PATTERNS: How this code is typically used and integrated\n\
4. GENERATION_GUIDANCE: How to generate similar high-quality code\n\n\
Focus on actionable insights for code generation and understanding.",
query, context
);
let result = self.generate_analysis(&prompt, Some(
"You are providing semantic code analysis for powerful LLMs. Focus on understanding code purpose, patterns, and architectural context."
)).await?;
Ok(result.text)
}
async fn detect_patterns(&self, code_samples: &[String]) -> LLMResult<String> {
let prompt = format!(
"Analyze these code samples for patterns and conventions:\n\n\
CODE SAMPLES:\n{}\n\n\
Provide structured pattern analysis:\n\
1. IDENTIFIED_PATTERNS: What consistent patterns are used\n\
2. QUALITY_ASSESSMENT: Quality and adherence to best practices\n\
3. TEAM_CONVENTIONS: Team-specific conventions and standards\n\
4. GENERATION_TEMPLATES: How to generate code following these patterns\n\n\
Focus on actionable guidance for consistent code generation.",
code_samples.join("\n---\n")
);
let result = self.generate_analysis(&prompt, Some(
"You are analyzing code patterns for consistency and quality. Provide actionable guidance for code generation."
)).await?;
Ok(result.text)
}
async fn analyze_impact(&self, target_code: &str, dependencies: &str) -> LLMResult<String> {
let prompt = format!(
"Analyze the impact of modifying this code:\n\n\
TARGET CODE:\n{}\n\n\
DEPENDENCIES:\n{}\n\n\
Provide structured impact analysis:\n\
1. RISK_ASSESSMENT: Risk level and reasoning\n\
2. AFFECTED_COMPONENTS: What will be impacted\n\
3. TESTING_REQUIREMENTS: Tests that need updating\n\
4. SAFETY_RECOMMENDATIONS: How to make changes safely\n\n\
Focus on safe implementation guidance.",
target_code, dependencies
);
let result = self.generate_analysis(&prompt, Some(
"You are providing critical impact analysis for code changes. Prioritize safety and thoroughness."
)).await?;
Ok(result.text)
}
}