agentleFS
yui-synth-labyui-synth-lab/obsidian-weaklog-processor/.claude/skills/llm-integration/SKILL.md

llm-integration

Skill0 starsChanged 10 months agoMITView on GitHub

Patterns for integrating Claude API and prompt engineering

  • Installs packages

12 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use ci-cd-pipelines, database-design and 3 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • harrissohail6Skill

    ci-cd-pipelines

    CI/CD pipeline design and implementation. Auto-activates when discussing deployment, automation, or pipelines.

    Also in 3 projects that use this

  • harrissohail6Skill

    database-design

    Database schema design and SQL best practices. Use when designing tables, writing queries, or optimizing database performance.

    Also in 3 projects that use this

  • MicrosoftSkill

    api-design

    Guide for designing and documenting RESTful APIs. Use when asked to design an API, create endpoints, or document an API.

    Also in 5 projects that use this

  • Microsoft AzureSkill

    git-workflow

    Squad branching model: dev-first workflow with insiders preview channel

    Also in 6 projects that use this

  • NVIDIASkill

    testing

    Run Python and Rust tests for physicsnemo-curator using uv + pytest with coverage reporting via pytest-cov, and cargo-nextest for Rust tests. Includes benchmark workflows with pytest-benchmark and criterion.

    Also in 4 projects that use this

The file

We split this skill into the rules it gives an agent

6 rules. 0 are common, 6 are distinctive, and 0 are very specific to this project.

  • 0

    Common

    Most of the 9 edited versions we read keep these.

  • 6

    Distinctive

    This author's own choices. Worth a look.

  • 0

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Use lower max_tokens when possible

    line 225
  2. Distinctive:

    Use Haiku model for simpler tasks (future feature)

    line 227
  3. Distinctive:

    Test with sample inputs

    line 255
  4. Distinctive:

    Test error scenarios (invalid key, timeout, malformed JSON)

    line 257
  5. Distinctive:

    Validate API responses: Check for malicious content injection

    line 262
  6. Distinctive:

    User data: Never send sensitive personal data to API without consent

    line 264

“Common” is measured: kept by at least 6 in 10 of the 9 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

LLM Integration Skill

This skill provides patterns and best practices for integrating the Anthropic Claude API into applications.

Anthropic API Setup

Installation

npm install @anthropic-ai/sdk

Basic Client

import Anthropic from '@anthropic-ai/sdk';

class LLMClient {
  private client: Anthropic;

  constructor(apiKey: string) {
    this.client = new Anthropic({
      apiKey: apiKey,
    });
  }

  async complete(prompt: string, options?: CompletionOptions): Promise<string> {
    try {
      const message = await this.client.messages.create({
        model: options?.model || 'claude-3-5-sonnet-20241022',
        max_tokens: options?.maxTokens || 1024,
        temperature: options?.temperature || 0.7,
        messages: [
          {
            role: 'user',
            content: prompt
          }
        ]
      });

      return message.content[0].type === 'text'
        ? message.content[0].text
        : '';
    } catch (error) {
      console.error('[LLM Error]', error);
      throw new Error(`API request failed: ${error.message}`);
    }
  }
}

Structured Output Pattern

JSON Response Parsing

async analyzeWithJSON<T>(
  prompt: string,
  schema: string
): Promise<T> {
  const fullPrompt = `${prompt}\n\n${schema}\n\nRespond ONLY with valid JSON matching this schema.`;

  const response = await this.complete(fullPrompt, {
    temperature: 0.3, // Lower for structured output
    maxTokens: 2000
  });

  try {
    // Extract JSON from markdown code blocks if present
    const jsonMatch = response.match(/```json\n([\s\S]*?)\n```/);
    const jsonText = jsonMatch ? jsonMatch[1] : response;

    return JSON.parse(jsonText) as T;
  } catch (error) {
    console.error('[JSON Parse Error]', response);
    throw new Error('Failed to parse JSON response from LLM');
  }
}

Usage Example

interface TriageResult {
  checks: {
    hasSpecifics: { pass: boolean; reason: string };
    canBeCorePhrase: { pass: boolean; reason: string };
    isTransferable: { pass: boolean; reason: string };
    isNonHarmful: { pass: boolean; reason: string };
  };
  score: number;
  recommendation: 'adopt' | 'review' | 'reject';
  coreQuestion: string;
}

const schema = `
{
  "checks": {
    "hasSpecifics": { "pass": boolean, "reason": "string (30 chars max)" },
    ...
  },
  "score": number,
  "recommendation": "adopt" | "review" | "reject",
  "coreQuestion": "string (40 chars max)"
}
`;

const result = await client.analyzeWithJSON<TriageResult>(prompt, schema);

Prompt Engineering Patterns

Clear Instructions

const TRIAGE_PROMPT = `
You are an AI judge evaluating personal writings for creative transformation.

Evaluate the following text against 4 criteria:

---
{text}
---

CRITERIA:
1. Has specifics: Contains concrete situations, not abstract thoughts
2. Can be core phrase: Can condense to one essential question (<40 chars)
3. Is transferable: Has universal relevance, not overly personal
4. Is non-harmful: Constructive, won't harm readers

OUTPUT FORMAT:
Respond with ONLY valid JSON matching this structure:
{
  "checks": {
    "hasSpecifics": { "pass": true/false, "reason": "max 30 chars" },
    "canBeCorePhrase": { "pass": true/false, "reason": "max 30 chars" },
    "isTransferable": { "pass": true/false, "reason": "max 30 chars" },
    "isNonHarmful": { "pass": true/false, "reason": "max 30 chars" }
  },
  "score": 0-4,
  "recommendation": "adopt" | "review" | "reject",
  "coreQuestion": "one sentence, 40 chars max"
}
`;

Temperature Guidelines

  • 0.0-0.3: Deterministic, factual (analysis, classification, JSON output)
  • 0.4-0.7: Balanced (general questions, moderate creativity)
  • 0.8-1.0: Creative (brainstorming, diverse outputs)

For this project:

  • Triage: 0.3 (objective evaluation)
  • Synthesis questions: 0.7 (creative exploration)

Error Handling

Robust API Calls

async callWithRetry<T>(
  fn: () => Promise<T>,
  maxRetries = 3,
  delay = 1000
): Promise<T> {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await fn();
    } catch (error) {
      const isLastAttempt = i === maxRetries - 1;

      // Don't retry on auth errors
      if (error.status === 401 || error.status === 403) {
        throw new Error('Invalid API key');
      }

      if (isLastAttempt) {
        throw error;
      }

      // Exponential backoff
      await new Promise(resolve => setTimeout(resolve, delay * Math.pow(2, i)));
    }
  }

  throw new Error('Max retries exceeded');
}

User-Facing Error Messages

try {
  const result = await triageAnalyzer.analyze(text);
} catch (error) {
  if (error.message.includes('Invalid API key')) {
    new Notice('API key is invalid. Check plugin settings.', 5000);
  } else if (error.message.includes('timeout')) {
    new Notice('Request timed out. Please try again.', 5000);
  } else {
    new Notice('AI analysis failed. You can triage manually.', 5000);
  }

  // Fallback to manual mode
  return null;
}

Cost Management

Token Estimation

  • 1 token ≈ 4 characters (English)
  • 1000 tokens ≈ 750 words

For this project:

  • Triage prompt: ~500 tokens
  • Synthesis prompt: ~300 tokens
  • Responses: 500-1000 tokens

Cost per Operation (Claude 3.5 Sonnet)

  • Input: $3 per million tokens
  • Output: $15 per million tokens

Estimated cost per weaklog entry: $0.01-0.02

Optimization

  • Use lower max_tokens when possible
  • Cache prompts for repeated calls (future feature)
  • Use Haiku model for simpler tasks (future feature)

Testing LLM Integration

Mock Client for Testing

class MockLLMClient extends LLMClient {
  async complete(prompt: string): Promise<string> {
    // Return deterministic responses for testing
    if (prompt.includes('evaluate')) {
      return JSON.stringify({
        checks: {
          hasSpecifics: { pass: true, reason: "Test reason" },
          // ...
        },
        score: 4,
        recommendation: "adopt",
        coreQuestion: "Test question?"
      });
    }

    return "Mock response";
  }
}

Integration Testing

  1. Set up test API key in environment
  2. Test with sample inputs
  3. Validate JSON parsing
  4. Test error scenarios (invalid key, timeout, malformed JSON)

Security

  • Never log API keys: Redact in console/debug output
  • Validate API responses: Check for malicious content injection
  • Rate limiting: Respect API rate limits (50 requests/min for tier 1)
  • User data: Never send sensitive personal data to API without consent

Resources

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.