﻿# Double AI agents: What's hiding in your Golang code

Today, almost everyone has got a taste of the vibe code, and some have gone a step further by setting up their own AI agents for projects\. Meanwhile, headlines are buzzing about how some AI agents deleted databases with all backups\. Now, we look at the source code for projects that are related in some way to agent\-based development\.

![1377_GolangDoubleAgent/image1.png](https://import.viva64.com/docx/blog/1377_GolangDoubleAgent/image1.png)

## Intro

Agent\-based development and various AI solutions are becoming increasingly common in software development\. We took PVS\-Studio Go analyzer and set it up to inspect AI\-driven projects, like different on\-premise AI models, load balancers, subscription proxy services, and others\. These aren't just random projects; they're actively used and in demand\.


> Want to try our Go analyzer on your projects? Join the \[Early Access Program\]\(https://pvs\-studio\.com/en/pvs\-studio\-eap/\)\\\. The EAP is currently available for JavaScript, TypeScript, and Go\\\.



As said one wise man, let's make hay while the sun shines\. In our case, go ahead with the project analysis\.

## Project analysis

### New\-api

And we start with [New API](https://github.com/QuantumNous/new-api), an LLM gateway and AI asset management system that manages a plethora of API keys from various providers through a single gateway\. This case shows that even a large\-scale and popular project like this one \(33,000 GitHub stars\) can contain bugs and suspicious code\. 

Commit: [`22b6b16`](https://github.com/QuantumNous/new-api/tree/22b6b16702b7a9a5a751d73b2641b334050f2206)\.

```cpp
func GetChannel(group string, model string, retry int) (*Channel, error) {
  var abilities []Ability

  var err error = nil
  channelQuery, err := getChannelQuery(group, model, retry)
  if err != nil {
    return nil, err
  }
  if common.UsingSQLite || common.UsingPostgreSQL {
    err = channelQuery.Order("weight DESC").Find(&abilities).Error
  } else {
    err = channelQuery.Order("weight DESC").Find(&abilities).Error
  }
  ....
}
```

The PVS\-Studio warning: [V8005](https://pvs-studio.com/en/docs/warnings/v8005/) The 'then' statement is equivalent to the 'else' statement\. [ability\.go 114](https://github.com/QuantumNous/new-api/blob/5dd0d3bcbd7b1d523bd046a5f9cf9fc8ce28d579/model/ability.go#L114)

The analyzer detected that the `if` statement with the `common.UsingSQLite || common.UsingPostgreSQL` condition may be meaningless, since the same code is executed in both the `then` and `else` clauses\.

PVS\-Studio found a similar issue in the following code snippet:

```cpp
func StreamResponseClaude2OpenAI(....) .... {
  ....
  if claudeResponse.Type == "message_start" {
    ....
  } else if claudeResponse.Type == "content_block_start" {
    ....
  } else if claudeResponse.Type == "content_block_delta" {
    ....
  } else if claudeResponse.Type == "message_delta" {
    ....
  } else if claudeResponse.Type == "message_stop" {
    return nil
  } else {
    return nil
  }
  ....
}
```

The PVS\-Studio warning: [V8005](https://pvs-studio.com/en/docs/warnings/v8005/) The 'then' statement is equivalent to the 'else' statement\. [relay\-claude\.go 474](https://github.com/QuantumNous/new-api/blob/5dd0d3bcbd7b1d523bd046a5f9cf9fc8ce28d579/relay/channel/claude/relay-claude.go#L507)

It looks like an error, but we can't say for sure just yet—maybe the logic for `claudeResponse.Type == "message_stop"` hasn't been implemented yet\. 

### Tau

Now PVS\-Studio inspects the [Tau](https://github.com/taubyte/tau) project, an open\-source platform for building self\-hosted cloud infrastructures\. 

Commit: [`1e5036f`](https://github.com/taubyte/tau/tree/1e5036ffab19efee73a50c5b0453756995bcb7bf)\.

```cpp
func (p *pluginInstance) makeFunc(....) reflect.Value {
  ....
  _out := make([]reflect.Value, len(cOut))
  for idx := 0; idx < len(cOut); idx++ {
    switch retTypes[idx] {
    case vm.I32Type:
      _out[idx] = reflect.ValueOf(int32(cOut[idx]))
    case vm.I64Type:                                            // <=
      _out[idx] = reflect.ValueOf(int64(cOut[idx]))
    case vm.F32Type:
      _out[idx] = reflect.ValueOf(math.Float32frombits(uint32(cOut[idx])))
    case vm.I64Type:                                            // <=
      _out[idx] = reflect.ValueOf(math.Float64frombits(cOut[idx]))
    }
  }
  ....
}
```

The PVS\-Studio warning: V8010 Two or more case branches have equivalent expressions\. [instance\.go 93](https://github.com/taubyte/tau/blob/c080c757c12b4156cc950c26bca17d40ac950003/pkg/vm-orbit/satellite/vm/instance.go#L93)

The same `I64Type` expression is used in multiple `case` statements, which makes no sense because the code inside the second case will never be executed\. And most likely, `F64Type` should be used instead of the second `I64Type`:

```cpp
switch retTypes[idx] {
  case vm.I32Type:
    _out[idx] = reflect.ValueOf(int32(cOut[idx]))
  case vm.I64Type:
    _out[idx] = reflect.ValueOf(int64(cOut[idx]))
  case vm.F32Type:
    _out[idx] = reflect.ValueOf(math.Float32frombits(uint32(cOut[idx])))
  case vm.F64Type: 
    _out[idx] = reflect.ValueOf(math.Float64frombits(cOut[idx]))
 }
```

We found a similar error pattern in the code of the popular ads blocker [AdGuardHome](https://github.com/AdguardTeam/AdGuardHome)\. We even wrote an article: [Go vet can't go\. How PVS\-Studio analyzes Go projects](https://pvs-studio.com/en/blog/posts/go/1342/#ID5543A82B01)\.

### Sub2api

Move on to the proxy server for AI services, [Sub2API](https://github.com/Wei-Shaw/sub2api)\. 

Commit: [`0f03393`](https://github.com/Wei-Shaw/sub2api/tree/0f0339301022c18ec7527382d1c7edc7b2933c8f)\.

```cpp
func cleanJSONSchemaRecursive(value any) any {
  ....
  if hasKey(schemaMap, "properties") {
    schemaMap["type"] = "object"
  } else {
  // 默认为 string ? or object? Gemini 通常需要明确 type
    schemaMap["type"] = "object"
  }
  ....
}
```

The PVS\-Studio warning: [V8005](https://pvs-studio.com/en/docs/warnings/v8005/) The 'then' statement is equivalent to the 'else' statement\. [schema\_cleaner\.go 310](https://github.com/Wei-Shaw/sub2api/blob/f5bd25bea045e728846b38bf18080ffa48d133c6/backend/internal/pkg/antigravity/schema_cleaner.go#L310)

There may be an error in either the `then` or `else` branch of this code snippet, as both sections are identical\. At best, the `if` statement is redundant and only makes the code more complicated\.

Look at another code fragment:

```cpp
func classifyOpsPhase(errType, message, code string) string {
  ....

  switch errType {
  case "authentication_error":
    return "auth"
  case "billing_error", "subscription_error":
    return "request"                                  // <=         
  case "rate_limit_error":
    if .... {
      return "request"
    }
    return "upstream"
  case "invalid_request_error":
    return "request"                                  // <=
  case "upstream_error", "overloaded_error":
    return "upstream"
  case "api_error":
    if strings.Contains(msg, opsErrNoAvailableAccounts) {
      return "routing"
    }
    return "internal"
  default:
    return "internal"
  }
}
```

The PVS\-Studio warning: [V8009](https://pvs-studio.com/en/docs/warnings/v8009/) Two or more case branches perform the same actions\. [ops\_error\_logger\.go 1125](https://github.com/Wei-Shaw/sub2api/blob/f5bd25bea045e728846b38bf18080ffa48d133c6/backend/internal/handler/ops_error_logger.go#L1125)

The analyzer found the `switch` branches with identical body\. The diagnostic rule is triggered quite often, since some cases require identical executable code, and some developers prefer not to use commas to list conditions\.

The first `case`, which returns the `request` value, contains several expressions: `case "billing_error", "subscription_error"`\. Here, it'd make sense to write the `case "invalid_request_error"` expression from the second `case` after a comma, since they should always result in the same outcome\.

We also couldn't ignore the following case:

```cpp
case "rate_limit_error":
    if .... {
      return "request"
    }
    return "upstream"
```

The `request` value can be returned, but we can see there is additional handling\. Maybe the second case, which has the same body, should also include some extra processing, but it's hard to tell from the context what exactly should be there, so the analyzer highlights the strange code fragment\.

We can notice the same case in the `classifyopsErrorSource` function:

```cpp
func classifyOpsErrorSource(phase string, message string) string {
  // Standardized sources: client_request|upstream_http|gateway
  switch phase {
  case "upstream":
    return "upstream_http"
  case "network":
    return "gateway"                                  // <=
  case "request", "auth":
    return "client_request"
  case "routing", "internal":
    return "gateway"                                  // <=
  default:
    if strings.Contains(strings.ToLower(message), "upstream") {
      return "upstream_http"
    }
    return "gateway"
  }
}
```

The PVS\-Studio warning: [V8009](https://pvs-studio.com/en/docs/warnings/v8009/) Two or more case branches perform the same actions\. [ops\_error\_logger\.go 1220](https://github.com/Wei-Shaw/sub2api/blob/f5bd25bea045e728846b38bf18080ffa48d133c6/backend/internal/handler/ops_error_logger.go#L1220)

On one hand, merging `case "routing", "internal"` and `case "network"` may not be a bad idea, but it looks like some code is missing here, just as in the `default` branch\.

### Photoprism

[PhotoPristm](https://github.com/photoprism/photoprism) is an open\-source, self\-hosted photo management app\. This project is interesting due to its built\-in AI capabilities and a REST API, which allow agents to manage the photo library\. 

Commit: [`93bb435`](https://github.com/photoprism/photoprism/tree/93bb435203a9338da6e781ec8d55e7cdde1aed21)\.

```cpp
func (c *opticsClusterer) extract() {
  ....
  switch {
  case math.Abs(d) <= c.xi:
    cs = areas[j].start
    ce = ue
  case d > c.xi:
    for k := areas[j].end; k > areas[j].end; k-- {                    // <=
      if ....{
        cs = k
        break
      }
    }
    ce = ue
  default:
    cs = areas[j].start
    for k := i; k < e; k++ {
      if ....{
        ce = k
        break
      }
    }
  }
  ....
}
```

The PVS\-Studio warning: V8016 The loop condition will never be met\. Inspect initial and final values in the 'for' loop\. [optics\.go 321](https://github.com/photoprism/photoprism/blob/464798234a9b7cfeb2ccda22d2f68b8103ea08ec/pkg/vector/alg/optics.go#L321)

The analyzer warns that the `for` condition will never be executed, since the start and end values are both equal to `areas[j].end`\. This is most likely a typo, and the condition should be as follows:

```cpp
for k := areas[j].end; k > areas[j].start; k-- {
  ....
}
```

### Axonhub

And here's another proxy, [Axonhub](https://github.com/looplj/axonhub)\. 

Commit: [`bfc11e01`](https://github.com/looplj/axonhub/tree/bfc11e0114f47726b271c9c800f9bcaa1557bf88)\.

```cpp
func AggregateStreamChunks(....) ([]byte, llm.ResponseMeta, error) {
  ....

  if event.Delta.Thinking != nil {
    if contentBlocks[index].Type == "thinking" {
      if contentBlocks[index].Thinking == nil {
        contentBlocks[index].Thinking = lo.ToPtr("")
      }

      *contentBlocks[index].Thinking += *event.Delta.Thinking
    } else {
      // Convert to thinking block if it's not already
      contentBlocks[index].Type = "thinking"
      contentBlocks[index].Thinking = event.Delta.Thinking
    }
  }

  if event.Delta.Signature != nil {                                      // <=
    // Handle signature delta - append to thinking block signature
    if contentBlocks[index].Type == "thinking" {
      if event.Delta.Signature != nil {                                  // <=
        if contentBlocks[index].Signature == nil {
          contentBlocks[index].Signature = event.Delta.Signature
        } else {
          contentBlocks[index].Signature = lo.ToPtr(....)
        }
      }
    } else {
      // Convert to thinking block if it's not already
      contentBlocks[index].Type = "thinking"
      contentBlocks[index].Signature = event.Delta.Signature
    }
  }

  ....
}
```

The PVS\-Studio warning: V8020 Recurring check\. The 'event\.Delta\.Signature \!\= nil' condition was already verified on line 96\. [aggregator\.go 96](https://github.com/looplj/axonhub/blob/aab5159add6b8876571e9a222ff25a73f471f7a2/llm/transformer/anthropic/aggregator.go#L96)

The analyzer detected a recursive check, `event.Delta.Signature != nil`\. Double check is meaningless because it's always true\.

### LocalAI

Now it's a [LocalAI](https://github.com/mudler/LocalAI) turn, an open\-source AI engine that allows running any model\. 

Commit: [`dd8e74a`](https://github.com/mudler/LocalAI/tree/dd8e74a486df34cdd2888f1643aecef0099d3a4a)\.

```cpp
func (r *RunCMD) Run(ctx *cliContext.Context) error {
  ....

  if r.DisableMetricsEndpoint {
    opts = append(opts, config.DisableMetricsEndpoint)
  }

  if r.DisableRuntimeSettings {
    opts = append(opts, config.DisableRuntimeSettings)
  }

  if r.EnableTracing {
    opts = append(opts, config.EnableTracing)
  }

  if r.EnableTracing {
    opts = append(opts, config.EnableTracing)
  }
  opts = append(opts, config.WithTracingMaxItems(r.TracingMaxItems))

  ....
}
```

The PVS\-Studio warning: [V8017](https://pvs-studio.com/en/docs/warnings/v8017/) The conditions of the 'if' statements situated alongside each other are equivalent\. Check lines: 158, 162\. [run\.go 158](https://github.com/mudler/LocalAI/blob/dd8e74a486df34cdd2888f1643aecef0099d3a4a/core/cli/run.go#L158)

We can see that the `Run` function duplicates strings:

```cpp
if r.EnableTracing {
    opts = append(opts, config.EnableTracing)
  }
```

This is most likely a bug that may cause `opts = append(opts, config.EnableTracing)` to be executed twice when `r.EnableTracing` is set to `true`\.

It's also possible that the second `r.EnableTracing` and `config.EnableTracing` should be something else, and some of the functionality is simply missing\. Maybe this is a copy\-pasting case\.

Let's move on to the next warning:

```cpp
func parseXMLWithFormat(s string, format *XMLToolCallFormat) (....) {
  ....

  for _, match := range toolCallMatches {
    if len(match) < 3 {
      continue
    }

    ....

    var functionContent string
    if len(match) >= 3 {
      if format.ToolSep == "" && format.KeyStart != "" {
        functionContent = match[2]
      } else {
        functionContent = match[2]
      }
    }
    ....
  }
  ....
}
```

The PVS\-Studio warning: [V8005](https://pvs-studio.com/en/docs/warnings/v8005/) The 'then' statement is equivalent to the 'else' statement\. [parse\.go 902](https://github.com/mudler/LocalAI/blob/dd8e74a486df34cdd2888f1643aecef0099d3a4a/pkg/functions/parse.go#L902)

The `then` and `else` blocks are identical, so there's no point in using `if` here\. 

Most likely, this is a copy\-paste error, where the developers forgot to update the index in the second line: `functionContent = match[2]`\.

As a result, [V8005](https://pvs-studio.com/en/docs/warnings/v8005/) immediately generated three warnings for three similar fragments:

```cpp
func ChatEndpoint(....) echo.HandlerFunc {
  ....
  if len(cleanedContent) > len(lastEmittedCleanedContent) &&  
    strings.HasPrefix(cleanedContent, lastEmittedCleanedContent) {
    deltaContent = cleanedContent[len(lastEmittedCleanedContent):]
    lastEmittedCleanedContent = cleanedContent
  } else if cleanedContent != lastEmittedCleanedContent {
    // If cleaned content changed but not in a simple append, 
    // extract delta from cleaned content
    // This handles cases where thinking tags are removed mid-stream
    if lastEmittedCleanedContent == "" {
      deltaContent = cleanedContent                             // <=
      lastEmittedCleanedContent = cleanedContent                // <=
    } else {
      // Content changed in non-append way, use the new cleaned content
      deltaContent = cleanedContent                             // <=
      lastEmittedCleanedContent = cleanedContent                // <=
    }
  }
  ....
}
```

The PVS\-Studio warning: [V8005](https://pvs-studio.com/en/docs/warnings/v8005/) The 'then' statement is equivalent to the 'else' statement\. chat\.go 85

And here we go again: the `then` and `else` blocks contain the same code\. However, this time there are three such blocks\. This suggests that the code may have been generated and then pulled into other functions\.

## Outro

That's all for now\. If you're interested in project checks focused on AI and agent\-based development, feel free to let us know in the comments :\)


> PVS\\\-Studio has recently launched the \[Early Access Program\]\(https://pvs\-studio\.com/en/pvs\-studio\-eap/\) for new analyzers, and you can join\\\! EAP is currently available for JavaScript, TypeScript, and Go\\\.



Want to check your project using PVS\-Studio? [Grab a trial](https://pvs-studio.com/en/pvs-studio/try-free/) and give it a try\!

Take care of yourself and your code\!