agentleFS
gollem-devgollem-dev/gollem/CLAUDE.md

gollem

CLAUDE.md199 starsChanged 6 months agoApache-2.0View on GitHub

When debugging tests, use the trace/logger package to enable LLM logging programmatically, or use zenv for environment-based configuration: gollem is a Go framework providing unified LLM access and agentic application building capabilities. Agent (gollem.go) - Central orchestrator managing conversation loops, tool execution, and session management. Entry point: gollem.New(llmClient, options...) LLM Clients (llm/) - Provider-specific implementations (OpenAI, Claude, Gemini, Ollama) that all implement the LLMClient interface with NewSession() and GenerateEmbedding() methods. Session Management (session.go) - Handles conversation state and message processing…

  • Reads credentials
  • In this repositoryOne other file it gives its agents.

The file

Show its rules and text

We split this CLAUDE.md into the rules it gives an agent

17 rules. About 0 are common, 4 are distinctive, and 13 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈4

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 13

    Very specific

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

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Do not export unnecessary methods, structs, and variables

    line 8
  2. Very specific:

    Use export_test.go for items that need to be exposed for testing purposes

    line 10
  3. Distinctive:

    When making changes, before finishing the task, always:

    line 11
  4. Very specific:

    Run go vet ./..., go fmt ./...

    line 12
  5. Very specific:

    Run golangci-lint run ./...

    line 13
  6. Very specific:

    Run gosec -quiet ./... to check security issue

    line 14
  7. Distinctive:

    Run tests to ensure no impact on other code

    line 15
  8. Distinctive:

    All comment and character literal in source code must be in English

    line 16
  9. Very specific:

    Test files should have package {name}_test.

    line 17
  10. Very specific:

    Test must be included in same name test file.

    line 18
  11. Very specific:

    Use named empty structure (e.g.

    line 19
  12. Very specific:

    Do not create binary. If you need to run, use go run command instead

    line 20
  13. Very specific:

    When a tmp directory is specified, search for files within the ./tmp directory relative to the project root.

    line 21
  14. Very specific:

    Test code may use os.Getenv() for test setup purposes

    line 27
  15. Very specific:

    When debugging tests, use the trace/logger package to enable LLM logging programmatically, or use zenv for environment-based configuration:

    line 47
  16. Very specific:

    MUST run go test ./... before completing any task

    line 54
  17. Very specific:

    Use export_test.go files to access internal packages for testing

    line 55

≈ “Common” is an estimate: at least 1 in 5 of the 12,729 CLAUDE.md files we read have a rule of the same kind, not the same words. “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
CLAUDE.md

CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

Restriction & Rules

  • In principle, do not trust developers who use this library from outside
    • Do not export unnecessary methods, structs, and variables
    • Assume that exposed items will be changed. Never expose fields that would be problematic if changed
    • Use export_test.go for items that need to be exposed for testing purposes
  • When making changes, before finishing the task, always:
    • Run go vet ./..., go fmt ./... to format the code
    • Run golangci-lint run ./... to check lint error
    • Run gosec -quiet ./... to check security issue
    • Run tests to ensure no impact on other code
  • All comment and character literal in source code must be in English
  • Test files should have package {name}_test. Do not use same package name
  • Test must be included in same name test file. (e.g. test for abc.go must be in abc_test.go)
  • Use named empty structure (e.g. type ctxHogeKey struct{} ) as private context key
  • Do not create binary. If you need to run, use go run command instead
  • When a tmp directory is specified, search for files within the ./tmp directory relative to the project root.
  • Naming Convention: In Go, package names already express the subject, so avoid redundancy in method/struct names
    • Good: openai.New(), claude.WithModel(), gemini.ThinkingLevel
    • Bad: openai.NewOpenAIClient(), claude.WithClaudeModel(), gemini.GeminiThinkingLevel
  • Environment Variables: Outside of test code, NEVER use os.Getenv() or os.LookupEnv() directly. Always use github.com/urfave/cli/v3 for environment variable access
    • This ensures proper configuration management and testability
    • Test code may use os.Getenv() for test setup purposes

Commands

Development and Testing

  • task or task mock - Generate mock files for testing (uses moq)
  • go test ./... - Run all tests (MUST run before exiting tasks)
  • go test -v ./llm/openai/ - Run tests for specific package
  • go test -v ./path/to/package - Run specific package tests when developing
  • go build ./... - Build all packages
  • go mod tidy - Clean up dependencies

Test Execution

Tests may require API keys for integration testing:

  • OpenAI: OPENAI_API_KEY
  • Anthropic: ANTHROPIC_API_KEY
  • Gemini: GEMINI_PROJECT_ID, GEMINI_LOCATION
  • Ollama: TEST_OLLAMA_MODEL (a model pulled to the server), optionally TEST_OLLAMA_BASE_URL and TEST_OLLAMA_EMBEDDING_MODEL

When debugging tests, use the trace/logger package to enable LLM logging programmatically, or use zenv for environment-based configuration:

# Run tests with debug profile
zenv -p debug go test -v ./strategy/planexec/ -run TestName

Code Quality

  • MUST run go test ./... before completing any task
  • Use export_test.go files to access internal packages for testing
  • Clean up any test binaries after checking

Architecture

gollem is a Go framework providing unified LLM access and agentic application building capabilities.

Core Components

Agent (gollem.go) - Central orchestrator managing conversation loops, tool execution, and session management. Entry point: gollem.New(llmClient, options...)

LLM Clients (llm/) - Provider-specific implementations (OpenAI, Claude, Gemini, Ollama) that all implement the LLMClient interface with NewSession() and GenerateEmbedding() methods.

Session Management (session.go) - Handles conversation state and message processing for each LLM interaction.

Tool System (tool.go) - Framework for LLM tool calling:

  • Tool interface: individual tools with Spec() and Run() methods
  • ToolSet interface: collections of tools (like MCP servers)
  • JSON Schema-based parameter validation

History Management (history.go) - Cross-provider conversation history with versioning and portable serialization for stateless applications.

MCP Integration (mcp/) - Model Context Protocol support for connecting to external tool servers via stdio or Streamable HTTP.

Facilitator (facilitator.go) - Controls session termination and provides the default respond_to_user tool for conversation completion.

Key Interfaces

type LLMClient interface {
    NewSession(ctx context.Context, options ...SessionOption) (Session, error)
    GenerateEmbedding(ctx context.Context, dimension int, input []string) ([][]float64, error)
}

type Session interface {
    Generate(ctx context.Context, input []Input, opts ...GenerateOption) (*Response, error)
    Stream(ctx context.Context, input []Input, opts ...GenerateOption) (<-chan *Response, error)
    History() (*History, error)
    AppendHistory(*History) error
    CountToken(ctx context.Context, input ...Input) (int, error)
}

type Tool interface {
    Spec() ToolSpec
    Run(ctx context.Context, args map[string]any) (map[string]any, error)
}

type ToolSet interface {
    Specs(ctx context.Context) ([]ToolSpec, error)
    Run(ctx context.Context, name string, args map[string]any) (map[string]any, error)
}

Structured Queries

  • Query[T]() — One-shot structured query. Creates a new session, calls LLM with JSON schema, unmarshals into T.
  • SessionQuery[T]() — Structured query on an existing session. Reuses conversation context via per-call GenerateOption (ResponseSchema). History is preserved across calls.
  • Per-call GenerateOption (e.g. WithMaxTokens, WithGenerateResponseSchema) can override session defaults for a single Generate/Stream call.

### LLM Provider Support

Each provider in `llm/` handles format conversion between gollem's unified interface and provider-specific APIs:
- **OpenAI**: GPT models with function calling
- **Claude**: Anthropic models with tool use
- **Gemini**: Google Vertex AI models with function calling
- **Ollama**: Models served by an Ollama server through its native API (`/api/chat`, `/api/embed`), over plain `net/http`

### Testing Patterns

- Mock generation using `moq` for interfaces (stored in `mock/`)
- Provider-specific conversion tests (`convert_test.go` in each LLM package)
- Integration tests that use real APIs when keys are available
- Export tests for testing internal functionality
- Private methods can be exported for testing via `export_test.go` (e.g., `var IsTokenLimitError = isTokenLimitError`)

### Examples

See `examples/` directory for usage patterns:
- `basic/` - Simple agent with tools
- `chat/` - Interactive conversation
- `embedding/` - Vector generation
- `mcp/` - MCP server integration
- `tools/` - Custom tool creation
- `plan_mode/` - Plan mode agent with goal-oriented task execution
- `query/` - Type-safe structured query with `Query[T]()`
- `simple/` - Minimal example

## Development Guidelines

### Error Handling
Use `github.com/m-mizutani/goerr/v2` for error wrapping:
```go
if err := validateData(t.Data); err != nil {
    return goerr.Wrap(err, "failed to validate data", goerr.Value("name", t.Name))
}

Testing Framework

  • Use github.com/m-mizutani/gt for testing (leverages Go generics)
  • Use Helper Driven Testing style instead of Table Driven Tests
  • All comments and literals MUST be in English

Example test pattern:

type testCase struct {
    input    string
    expected string
}

runTest := func(tc testCase) func(t *testing.T) {
    return func(t *testing.T) {
        actual := someFunc(tc.input)
        gt.Equal(t, tc.expected, actual)
    }
}

t.Run("success case", runTest(testCase{
    input: "blue",
    expected: "BLUE",
}))

Logging

LLM Request and Response Logging

gollem provides detailed logging via the trace/logger package, which implements trace.Handler and outputs structured logs through slog.Logger.

Setup

import tracelogger "github.com/gollem-dev/gollem/trace/logger"

// Enable all events (default)
handler := tracelogger.New()

// Or enable specific events only
handler := tracelogger.New(
    tracelogger.WithEvents(tracelogger.LLMRequest, tracelogger.LLMResponse),
)

agent := gollem.New(client, gollem.WithTraceHandler(handler))

Available Events

  • AgentExec - Agent execution start/end
  • LLMRequest - LLM request prompts
  • LLMResponse - LLM response content
  • ToolExec - Tool execution start/end
  • SubAgent - Sub-agent execution start/end
  • ChildAgent - Child agent execution start/end
  • CustomEvent - Custom trace events

Log Structure

Logs use structured format via slog at the DEBUG level:

{
  "level": "DEBUG",
  "msg": "llm call",
  "duration": "1.234s",
  "model": "claude-3-sonnet-20240229",
  "input_tokens": 150,
  "output_tokens": 75,
  "request": { ... },
  "response": { ... }
}

Benefits

  • Debugging: Track exact prompts and responses during development
  • Monitoring: Observe token usage and response patterns
  • Audit: Log tool calls and function executions
  • Performance: Analyze response times and token efficiency
  • Troubleshooting: Capture complete interaction context for issue resolution

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.