Skip to main content

Recent Posts

/**
 * Analyzes code using the Ollama API and returns a description and suggestions.
 * If the analysis is valid JSON, it is inserted into the AiDescriptions table.
 * @param code The code snippet to analyze.
 * @param language The programming language of the code.
 * @param postId (optional) The ID of the post being analyzed.
 * @returns An object containing description and suggestions.
 */
async function analyzeCodeWithOllama(
  code: string,
  language: string,
  postId?: string
): Promise<CodeAnalysisResponse> {
  if (!code || !language) {
    throw new Error('Code and language are required');
  }
  try {
    const prompt = createPrompt(code, language);
    const response: AxiosResponse = await axios.post(OLLAMA_API_URL, {
      model: MODEL_NAME,
      prompt,
      stream: false,
      think: false,
    });
    console.log('Raw Ollama response:', JSON.stringify(response.data, null, 2));
    let analysis: CodeAnalysisResponse;
    try {
      const responseText = typeof response.data === 'string' ? response.data : response.data.response || JSON.stringify(response.data);
      const jsonMatch = responseText.match(/{[\s\S]*}/);
      if (jsonMatch) {
        analysis = JSON.parse(jsonMatch[0]);
        // If valid JSON and postId is provided, insert into DB
        if (postId && analysis.description) {
          try {
            await insertAiDescription(postId, analysis.description, analysis.suggestions, new Date().toISOString());
          } catch (dbErr: any) {
            console.error(`Failed to insert AI description for post ${postId}:`, dbErr.message);
          }
        }
      } else {
        throw new Error('No valid JSON found in response');
      }
    } catch (parseError) {
      console.error('Error parsing Ollama response:', parseError, 'Response:', response.data);
      throw new Error('Failed to parse model response');
    }
    if (!analysis.description || !Array.isArray(analysis.suggestions)) {
      console.error('Invalid response format:', analysis);
      throw new Error('Invalid response format from model');
    }
    return analysis;
  } catch (error: any) {
    console.error('Error communicating with Ollama:', error.message);
    throw new Error('Failed to analyze code: ' + error.message);
  }
}
import subprocess
import re

def parse_bgp_route(prefix="[IP_ADDRESS]"):
    try:
        # Construct and execute vtysh command
        vtysh_command = f'show ip bgp {prefix}'
        process = subprocess.Popen(['vtysh', '-c', vtysh_command],
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE,
                                 text=True)
        output, error = process.communicate()
        
        if process.returncode != 0:
            return f"Error: {error}"

        # Initialize dictionary for BGP attributes
        bgp_info = {
            'next_hop': None,
            'as_path': [],
            'local_pref': None,
            'weight': None
        }

        # Parse the output using regex patterns
        lines = output.split('\n')
        for line in lines:
            # Get next hop IP
            if 'from' in line:
                next_hop_match = re.search(r'(\d+\.\d+\.\d+\.\d+) from', line)
                if next_hop_match:
                    bgp_info['next_hop'] = next_hop_match.group(1)

            # Get local pref, weight, and AS path
            if 'localpref' in line:
                # Extract local preference
                local_pref_match = re.search(r'localpref (\d+)', line)
                if local_pref_match:
                    bgp_info['local_pref'] = int(local_pref_match.group(1))

                # Extract weight
                weight_match = re.search(r'weight (\d+)', line)
                if weight_match:
                    bgp_info['weight'] = int(weight_match.group(1))

                # AS path would be empty for local routes
                # For routes with AS path, you would see numbers between the 'from' and 'Origin'
                as_path_match = re.search(r'from.*?(\d+[\s\d+]*)?Origin', line)
                if as_path_match and as_path_match.group(1):
                    bgp_info['as_path'] = [int(asn) for asn in as_path_match.group(1).split()]

        return bgp_info

    except Exception as e:
        return f"Error executing command: {str(e)}"

# Example usage
if __name__ == "__main__":
    result = parse_bgp_route()
    print("BGP Route Information:")
    print(f"Next Hop: {result['next_hop']}")
    print(f"AS Path: {result['as_path']}")
    print(f"Local Preference: {result['local_pref']}")
    print(f"Weight: {result['weight']}")

Post Statistics