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.
- test-with-gtSkill
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
- Distinctive: line 8
Do not export unnecessary methods, structs, and variables
- Very specific: line 10
Use export_test.go for items that need to be exposed for testing purposes
- Distinctive: line 11
When making changes, before finishing the task, always:
- Very specific: line 12
Run go vet ./..., go fmt ./...
- Very specific: line 13
Run golangci-lint run ./...
- Very specific: line 14
Run gosec -quiet ./... to check security issue
- Distinctive: line 15
Run tests to ensure no impact on other code
- Distinctive: line 16
All comment and character literal in source code must be in English
- Very specific: line 17
Test files should have package {name}_test.
- Very specific: line 18
Test must be included in same name test file.
- Very specific: line 19
Use named empty structure (e.g.
- Very specific: line 20
Do not create binary. If you need to run, use go run command instead
- Very specific: line 21
When a tmp directory is specified, search for files within the ./tmp directory relative to the project root.
- Very specific: line 27
Test code may use os.Getenv() for test setup purposes
- Very specific: line 47
When debugging tests, use the trace/logger package to enable LLM logging programmatically, or use zenv for environment-based configuration:
- Very specific: line 54
MUST run go test ./... before completing any task
- Very specific: line 55
Use export_test.go files to access internal packages for testing
≈ “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.
Files
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.gofor 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
- Run
- 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.gomust be inabc_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 runcommand instead - When a
tmpdirectory is specified, search for files within the./tmpdirectory 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
- Good:
- Environment Variables: Outside of test code, NEVER use
os.Getenv()oros.LookupEnv()directly. Always usegithub.com/urfave/cli/v3for environment variable access- This ensures proper configuration management and testability
- Test code may use
os.Getenv()for test setup purposes
Commands
Development and Testing
taskortask 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 packagego test -v ./path/to/package- Run specific package tests when developinggo build ./...- Build all packagesgo 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), optionallyTEST_OLLAMA_BASE_URLandTEST_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 TestNameCode Quality
- MUST run
go test ./...before completing any task - Use
export_test.gofiles 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:
Toolinterface: individual tools withSpec()andRun()methodsToolSetinterface: 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-callGenerateOption(ResponseSchema). History is preserved across calls.- Per-call
GenerateOption(e.g.WithMaxTokens,WithGenerateResponseSchema) can override session defaults for a singleGenerate/Streamcall.
### 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/gtfor 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/endLLMRequest- LLM request promptsLLMResponse- LLM response contentToolExec- Tool execution start/endSubAgent- Sub-agent execution start/endChildAgent- Child agent execution start/endCustomEvent- 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
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
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.

