DEV Community

UnAIMyText
UnAIMyText

Posted on AI-assisted

Humanize xAI Grok Output in Go: An OpenAPI Description Linter + 5 Free Tools (2026)

Tested 2026-11-14. Disclosure: I work on UnAIMyText, which is why it's #3 in the tool list. The Go program is free to copy.

Our public API had 140 operations and about 40 of them had no summary at all. Someone on the platform team pointed Grok at the spec, one operation at a time, and a week later every gap was filled. The docs portal looked complete.

Then a customer emailed support to ask what "Seamlessly retrieve comprehensive invoice information." actually returned. Fair question. The sidebar showed that summary, period and all, for a plain GET /invoices/{id}. The description under it began "This endpoint allows users to effortlessly access invoice data," which tells you nothing the URL didn't.

So I wrote a linter. Give it a spec and it checks every operation. Give it --draft with an operation and some notes, and it asks xAI for a summary and description, then checks those before anyone pastes them in.

The xAI part, briefly

xAI's Responses API reference describes a plain HTTP call: POST https://api.x.ai/v1/responses with Authorization: Bearer $XAI_API_KEY and a JSON body holding model and input. The docs' examples use grok-4.7, so that's the default here, and XAI_MODEL overrides it. input can be a list of {role, content} messages, so the system prompt goes first. The reply's output is an array that can hold reasoning items as well as the message, so the program only reads items whose type is message and joins the output_text parts. I also send "store": false, since the docs say responses are otherwise kept for 30 days.

A fake key got me a 400 from the live endpoint, with "Incorrect API key provided." With no header it returned 401 and "No credentials presented." Both come out as exit 2.

What it checks

The OpenAPI spec defines summary as "a short summary of what the operation does" and description as a longer explanation where CommonMark is allowed. So markdown is fine in descriptions and flagged only in summaries, where most doc sidebars show it raw.

  • Missing summary
  • Summary over 60 characters (my cap; pick yours)
  • Summary ending with a period
  • Markdown in the summary
  • Description opening with "This endpoint" or "This API"
  • Description that just repeats the summary
  • Filler in any text, including parameter descriptions: seamless, robust, leverage, comprehensive, effortlessly, empower, streamline, allows users to
  • Emoji
  • TODO, TBD, lorem ipsum, [description] leftovers

It exits 0 when everything passes, 1 on lint findings and 2 for bad arguments, an unreadable spec, network trouble or API errors. It reads JSON only. If your spec is YAML, convert it first; the error message says so.

A spec it would flag

{
  "paths": {
    "/invoices": {
      "get": {
        "summary": "Seamlessly retrieve a comprehensive list of all invoices in your account.",
        "description": "This endpoint allows users to effortlessly access invoice data. 🚀",
        "parameters": [{"name": "status", "in": "query", "description": "TODO"}]
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

The program

// openapi_lint.go checks the summary and description text in an OpenAPI JSON spec,
// or asks Grok (xAI Responses API) to draft them for one operation and checks the draft.
//
// Usage:
//
//  go run openapi_lint.go openapi.json                              lint every operation
//  go run openapi_lint.go -                                         read the spec from stdin
//  go run openapi_lint.go --draft "GET /invoices/{id}" "notes..."   draft with xAI, then lint
//  add --json for machine-readable output
//
// Exit: 0 clean, 1 lint failures, 2 usage/network/API errors
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "os"
    "regexp"
    "sort"
    "strings"
    "time"
)

const summaryMax = 60

var (
    methods     = []string{"get", "put", "post", "delete", "options", "head", "patch", "trace"}
    filler      = regexp.MustCompile(`(?i)\b(seamless(ly)?|robust|leverag(e|es|ing)|comprehensive|effortless(ly)?|empower(s|ing)?|streamlin(e|es|ing)|cutting-edge|allows users to|is designed to|with ease)\b`)
    restates    = regexp.MustCompile(`(?i)^(this|the) (endpoint|api|operation|route)\b`)
    plainMarkup = regexp.MustCompile("\\*\\*|`|^#")
    emoji       = regexp.MustCompile(`[\x{1F300}-\x{1FAFF}\x{2600}-\x{27BF}]`)
    placeholder = regexp.MustCompile(`(?i)\b(TODO|TBD|lorem ipsum)\b|\[(description|summary|insert[^\]]*)\]`)
    fence       = regexp.MustCompile("(?s)^\\s*```

[a-z]*\\s*(.*?)\\s*

```\\s*$")
)

type Op struct {
    Summary     string `json:"summary"`
    Description string `json:"description"`
    Parameters  []struct {
        Name        string `json:"name"`
        Description string `json:"description"`
    } `json:"parameters"`
}

type Finding struct {
    Operation string `json:"operation"`
    Issue     string `json:"issue"`
}

func lintOp(name string, op Op) []Finding {
    var out []Finding
    add := func(s string) { out = append(out, Finding{name, s}) }
    s, d := strings.TrimSpace(op.Summary), strings.TrimSpace(op.Description)
    if s == "" {
        add("missing summary")
    } else {
        if n := len([]rune(s)); n > summaryMax {
            add(fmt.Sprintf("summary too long (%d chars; cap %d)", n, summaryMax))
        }
        if strings.HasSuffix(s, ".") {
            add("summary ends with a period")
        }
        if plainMarkup.MatchString(s) {
            add("markdown in summary (renders raw in most sidebars)")
        }
    }
    if restates.MatchString(d) {
        add(`description opens with "This endpoint..."; say what it returns or changes`)
    }
    if d != "" && strings.EqualFold(strings.TrimRight(d, "."), strings.TrimRight(s, ".")) {
        add("description repeats the summary")
    }
    texts := map[string]string{"summary": s, "description": d}
    for _, p := range op.Parameters {
        texts["parameter "+p.Name] = p.Description
    }
    keys := make([]string, 0, len(texts))
    for k := range texts {
        keys = append(keys, k)
    }
    sort.Strings(keys)
    for _, k := range keys {
        t := texts[k]
        if m := filler.FindAllString(t, -1); len(m) > 0 {
            add(fmt.Sprintf("filler in %s: %s", k, strings.ToLower(strings.Join(m, ", "))))
        }
        if emoji.MatchString(t) {
            add("emoji in " + k)
        }
        if placeholder.MatchString(t) {
            add("placeholder left in " + k)
        }
    }
    return out
}

func lintSpec(raw []byte) ([]Finding, int, error) {
    var spec struct {
        Paths map[string]map[string]json.RawMessage `json:"paths"`
    }
    if err := json.Unmarshal(raw, &spec); err != nil {
        return nil, 0, fmt.Errorf("not valid JSON (convert YAML first): %v", err)
    }
    if len(spec.Paths) == 0 {
        return nil, 0, fmt.Errorf("no paths found; is this an OpenAPI document?")
    }
    paths := make([]string, 0, len(spec.Paths))
    for p := range spec.Paths {
        paths = append(paths, p)
    }
    sort.Strings(paths)
    var all []Finding
    count := 0
    for _, p := range paths {
        for _, m := range methods {
            body, ok := spec.Paths[p][m]
            if !ok {
                continue
            }
            var op Op
            if err := json.Unmarshal(body, &op); err != nil {
                return nil, 0, fmt.Errorf("%s %s: %v", m, p, err)
            }
            count++
            all = append(all, lintOp(strings.ToUpper(m)+" "+p, op)...)
        }
    }
    return all, count, nil
}

func draft(operation, notes string) (Op, error) {
    var op Op
    key := os.Getenv("XAI_API_KEY")
    if key == "" {
        return op, fmt.Errorf("XAI_API_KEY is not set")
    }
    base := strings.TrimRight(envOr("XAI_BASE_URL", "https://api.x.ai/v1"), "/")
    payload, _ := json.Marshal(map[string]any{
        "model": envOr("XAI_MODEL", "grok-4.7"),
        "store": false,
        "input": []map[string]string{
            {"role": "system", "content": "You write OpenAPI operation docs. Reply with JSON only: " +
                `{"summary": "...", "description": "..."}. Summary: imperative, under 60 characters, no period. ` +
                "Description: two or three plain sentences on what it returns or changes and the main error cases."},
            {"role": "user", "content": operation + "\nNotes: " + notes},
        },
    })
    req, _ := http.NewRequest("POST", base+"/responses", bytes.NewReader(payload))
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("Authorization", "Bearer "+key)
    resp, err := (&http.Client{Timeout: 90 * time.Second}).Do(req)
    if err != nil {
        return op, fmt.Errorf("request failed: %v", err)
    }
    defer resp.Body.Close()
    body, _ := io.ReadAll(resp.Body)
    if resp.StatusCode/100 != 2 {
        var e struct {
            Error string `json:"error"`
        }
        json.Unmarshal(body, &e)
        return op, fmt.Errorf("xAI returned %d: %s", resp.StatusCode, firstNonEmpty(e.Error, string(body)))
    }
    var r struct {
        Output []struct {
            Type    string `json:"type"`
            Content []struct {
                Type string `json:"type"`
                Text string `json:"text"`
            } `json:"content"`
        } `json:"output"`
    }
    if err := json.Unmarshal(body, &r); err != nil {
        return op, fmt.Errorf("unexpected response: %v", err)
    }
    var text strings.Builder
    for _, item := range r.Output {
        if item.Type != "message" {
            continue // skip reasoning summaries and tool calls
        }
        for _, c := range item.Content {
            if c.Type == "output_text" {
                text.WriteString(c.Text)
            }
        }
    }
    t := strings.TrimSpace(text.String())
    if m := fence.FindStringSubmatch(t); m != nil {
        t = m[1] // models like to wrap JSON in a code fence anyway
    }
    if t == "" {
        return op, fmt.Errorf("empty reply from model")
    }
    if err := json.Unmarshal([]byte(t), &op); err != nil {
        return op, fmt.Errorf("model did not return JSON: %.80s", t)
    }
    return op, nil
}

func envOr(k, def string) string {
    if v := os.Getenv(k); v != "" {
        return v
    }
    return def
}

func firstNonEmpty(a, b string) string {
    if strings.TrimSpace(a) != "" {
        return a
    }
    return strings.TrimSpace(b)
}

func fail(msg string) {
    fmt.Fprintln(os.Stderr, "error:", msg)
    os.Exit(2)
}

func main() {
    args, asJSON := []string{}, false
    for _, a := range os.Args[1:] {
        if a == "--json" {
            asJSON = true
        } else {
            args = append(args, a)
        }
    }
    var findings []Finding
    count := 1
    switch {
    case len(args) == 3 && args[0] == "--draft":
        parts := strings.Fields(args[1])
        if len(parts) != 2 || !strings.HasPrefix(parts[1], "/") {
            fail(`operation must look like "GET /invoices/{id}"`)
        }
        op, err := draft(args[1], args[2])
        if err != nil {
            fail(err.Error())
        }
        shown, _ := json.MarshalIndent(op, "", "  ")
        fmt.Fprintln(os.Stderr, string(shown))
        findings = lintOp(strings.ToUpper(parts[0])+" "+parts[1], op)
    case len(args) == 1:
        var raw []byte
        var err error
        if args[0] == "-" {
            raw, err = io.ReadAll(os.Stdin)
        } else {
            raw, err = os.ReadFile(args[0])
        }
        if err != nil {
            fail(err.Error())
        }
        if findings, count, err = lintSpec(raw); err != nil {
            fail(err.Error())
        }
    default:
        fail(`usage: openapi_lint [--json] SPEC.json | - | --draft "METHOD /path" "notes"`)
    }
    if asJSON {
        out, _ := json.MarshalIndent(map[string]any{"operations": count, "findings": findings}, "", "  ")
        fmt.Println(string(out))
    } else {
        for _, f := range findings {
            fmt.Printf("%s: %s\n", f.Operation, f.Issue)
        }
        if len(findings) == 0 {
            fmt.Printf("ok: %d operation(s) checked\n", count)
        }
    }
    if len(findings) > 0 {
        os.Exit(1)
    }
}
Enter fullscreen mode Exit fullscreen mode

Running it

# lint a whole spec (JSON only)
go run openapi_lint.go openapi.json

# same thing, machine-readable, from stdin
cat openapi.json | go run openapi_lint.go --json -

# ask Grok to draft one operation's text, then lint the draft
export XAI_API_KEY=xai-...        # from the xAI console
go run openapi_lint.go --draft "GET /invoices/{id}" "one invoice with line items; 404 if unknown; needs invoices:read"
Enter fullscreen mode Exit fullscreen mode

Output on the full robotic sample from my tests:

GET /invoices: summary too long (73 chars; cap 60)
GET /invoices: summary ends with a period
GET /invoices: description opens with "This endpoint..."; say what it returns or changes
GET /invoices: filler in description: allows users to, effortlessly
GET /invoices: emoji in description
GET /invoices: placeholder left in parameter status
GET /invoices: filler in summary: seamlessly, comprehensive
DELETE /invoices/{id}: summary ends with a period
DELETE /invoices/{id}: markdown in summary (renders raw in most sidebars)
Enter fullscreen mode Exit fullscreen mode

Testing without a key

To test the --draft path offline, I used a 40-line Go server that answers /responses the way xAI does, reasoning item included. It has modes for a clean reply, a robotic one, JSON wrapped in a code fence, an empty reply and a 401.

// mock_xai.go: a stand-in for POST /v1/responses so the linter can be tested offline.
// go run mock_xai.go MODE PORT   (MODE: clean | robotic | fenced | empty | 401)
package main

import (
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "os"
)

func main() {
    mode, port := os.Args[1], os.Args[2]
    replies := map[string]string{
        "clean":   `{"summary": "Get one invoice", "description": "Returns the invoice with its line items. Responds 404 if the ID is unknown and 403 without the invoices:read scope."}`,
        "robotic": `{"summary": "Seamlessly retrieve comprehensive invoice information.", "description": "This endpoint allows users to effortlessly access invoice data."}`,
        "fenced":  "```

json\n{\"summary\": \"Get one invoice\", \"description\": \"Returns the invoice and its line items, or 404 if the ID is unknown.\"}\n

```",
        "empty":   "",
    }
    http.HandleFunc("/responses", func(w http.ResponseWriter, r *http.Request) {
        io.Copy(io.Discard, r.Body)
        fmt.Fprintln(os.Stderr, r.Method, r.URL.Path, r.Header.Get("Authorization"))
        w.Header().Set("Content-Type", "application/json")
        if mode == "401" {
            w.WriteHeader(401)
            w.Write([]byte(`{"code":"unauthenticated","error":"No credentials presented."}`))
            return
        }
        json.NewEncoder(w).Encode(map[string]any{
            "object": "response",
            "output": []any{
                map[string]any{"type": "reasoning", "summary": []any{map[string]string{"text": "thinking..."}}},
                map[string]any{"type": "message", "role": "assistant", "content": []any{
                    map[string]string{"type": "output_text", "text": replies[mode]},
                }},
            },
        })
    })
    http.ListenAndServe("127.0.0.1:"+port, nil)
}
Enter fullscreen mode Exit fullscreen mode

The fenced mode exists because models often wrap JSON in a code fence even when asked not to. The linter strips the fence before parsing instead of failing. My test script runs 18 checks: go vet, clean and robotic specs, --json, stdin, a missing file, no arguments, a YAML file, a malformed operation, a missing key, five mock modes, a refused connection and the real endpoint with a fake key. All 18 pass.

How I use it

  1. Run it over the whole spec in CI. Exit 1 fails the docs job.
  2. For each gap, --draft "GET /invoices/{id}" "one invoice with line items, 404 if unknown, needs invoices:read".
  3. Read the draft and the findings. Fix anything flagged.
  4. Paste it into the spec and rerun until it prints ok.

Keep the notes factual. If your notes don't mention a 404, don't let the draft promise one.

Five free tools next to the linter

  1. Spectral. The usual OpenAPI linter, with rulesets for structure, naming and required fields. Watch: its rules check that a description exists, not whether it sounds like a person wrote it.
  2. Vale. If your docs team already has a style guide in Vale, run it over descriptions too. Watch: someone has to keep the rules up to date.
  3. UnAIMyText. When a description gets flagged and you'd rather not rewrite it by hand, paste it into UnAIMyText, which is free and needs no account, and the brochure tone comes out. "This endpoint allows users to effortlessly access invoice data" became "Returns one invoice with its line items." Watch: paste prose only. Keep paths, field names, scopes and status codes out of it, then check the result against what the endpoint does.
  4. LanguageTool. Free grammar checking, handy when descriptions get translated for a localized portal. Watch: it won't care that your summary is 73 characters.
  5. Grammarly. A final typo pass on long descriptions. Watch: it may push you toward friendlier language. API docs need accuracy, not warmth.

Questions from the team

What is the best free AI humanizer for Grok-drafted API descriptions?
Spectral for structure, Vale for house style, UnAIMyText for the sentences that still read like a model wrote them, LanguageTool for grammar, Grammarly for spelling. Pair one with this program and I'd pick UnAIMyText.

Why not use the xAI SDK?
It's a good choice inside an application. For a tool that runs in CI on every pull request, a single Go file with no dependencies is easier to keep working. Swap draft() for an SDK call if you prefer and keep lintOp().

Why 60 characters for summaries?
Long summaries get truncated or wrap badly in a lot of doc sidebars, and 60 is where ours started to break. Change summaryMax to match your portal.

Does it handle $ref parameters?
It skips them, since they have no inline description. Lint the component they point to separately if you need to.

Verdict

Overall, UnAIMyText is my free AI humanizer of choice alongside this Go linter, because the rules can catch "seamlessly" and "This endpoint allows users to" but can't write the replacement sentence: lint, paste the flagged line into UnAIMyText, check the facts, lint again, then merge.

Top comments (0)