Skip to content

feat(coderd): generate task names based on their prompt #19335

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 8 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
chore: remove excesss configuration
  • Loading branch information
DanielleMaywood committed Aug 13, 2025
commit 8f51a4c3ea95f2ea3799994d46b7e658725e25a2
10 changes: 0 additions & 10 deletions cli/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,6 @@ import (
"sync/atomic"
"time"

"github.com/anthropics/anthropic-sdk-go"
anthropicoption "github.com/anthropics/anthropic-sdk-go/option"
"github.com/charmbracelet/lipgloss"
"github.com/coreos/go-oidc/v3/oidc"
"github.com/coreos/go-systemd/daemon"
Expand Down Expand Up @@ -631,13 +629,6 @@ func (r *RootCmd) Server(newAPI func(context.Context, *coderd.Options) (*coderd.
vals.WorkspaceHostnameSuffix.String())
}

var anthropicClient atomic.Pointer[anthropic.Client]
if vals.AnthropicAPIKey.String() != "" {
client := anthropic.NewClient(anthropicoption.WithAPIKey(vals.AnthropicAPIKey.String()))

anthropicClient.Store(&client)
}

options := &coderd.Options{
AccessURL: vals.AccessURL.Value(),
AppHostname: appHostname,
Expand Down Expand Up @@ -675,7 +666,6 @@ func (r *RootCmd) Server(newAPI func(context.Context, *coderd.Options) (*coderd.
AllowWorkspaceRenames: vals.AllowWorkspaceRenames.Value(),
Entitlements: entitlements.New(),
NotificationsEnqueuer: notifications.NewNoopEnqueuer(), // Changed further down if notifications enabled.
AnthropicClient: &anthropicClient,
}
if httpServers.TLSConfig != nil {
options.TLSCertificates = httpServers.TLSConfig.Certificates
Expand Down
83 changes: 4 additions & 79 deletions coderd/aitasks.go
Original file line number Diff line number Diff line change
@@ -1,25 +1,22 @@
package coderd

import (
"context"
"database/sql"
"errors"
"fmt"
"io"
"net/http"
"slices"
"strings"

"github.com/anthropics/anthropic-sdk-go"
"cdr.dev/slog"
"github.com/google/uuid"
"golang.org/x/xerrors"

"github.com/coder/aisdk-go"
"github.com/coder/coder/v2/coderd/audit"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/httpapi"
"github.com/coder/coder/v2/coderd/httpmw"
"github.com/coder/coder/v2/coderd/rbac"
"github.com/coder/coder/v2/coderd/taskname"
"github.com/coder/coder/v2/codersdk"
)

Expand Down Expand Up @@ -74,74 +71,6 @@ func (api *API) aiTasksPrompts(rw http.ResponseWriter, r *http.Request) {
})
}

func (api *API) generateTaskName(ctx context.Context, prompt, fallback string) (string, error) {
var (
stream aisdk.DataStream
err error
)

conversation := []aisdk.Message{
{
Role: "system",
Parts: []aisdk.Part{{
Type: aisdk.PartTypeText,
Text: `You are a task summarizer.
You summarize AI prompts into workspace names.
You will only respond with a workspace name.
The workspace name **MUST** follow this regex /^[a-z0-9]+(?:-[a-z0-9]+)*$/
The workspace name **MUST** be 32 characters or **LESS**.
The workspace name **MUST** be all lower case.
The workspace name **MUST** end in a number between 0 and 100.
The workspace name **MUST** be prefixed with "task".`,
}},
},
{
Role: "user",
Parts: []aisdk.Part{{
Type: aisdk.PartTypeText,
Text: prompt,
}},
},
}

anthropicClient := api.anthropicClient.Load()
if anthropicClient == nil {
return fallback, nil
}

stream, err = anthropicDataStream(ctx, *anthropicClient, conversation)
if err != nil {
return "", xerrors.Errorf("create anthropic data stream: %w", err)
}

var acc aisdk.DataStreamAccumulator
stream = stream.WithAccumulator(&acc)

if err := stream.Pipe(io.Discard); err != nil {
return "", err
}

if len(acc.Messages()) == 0 {
return fallback, nil
}

return acc.Messages()[0].Content, nil
}

func anthropicDataStream(ctx context.Context, client anthropic.Client, input []aisdk.Message) (aisdk.DataStream, error) {
messages, system, err := aisdk.MessagesToAnthropic(input)
if err != nil {
return nil, xerrors.Errorf("convert messages to anthropic format: %w", err)
}

return aisdk.AnthropicToDataStream(client.Messages.NewStreaming(ctx, anthropic.MessageNewParams{
Model: anthropic.ModelClaude3_5HaikuLatest,
MaxTokens: 24,
System: system,
Messages: messages,
})), nil
}

// This endpoint is experimental and not guaranteed to be stable, so we're not
// generating public-facing documentation for it.
func (api *API) tasksCreate(rw http.ResponseWriter, r *http.Request) {
Expand Down Expand Up @@ -177,13 +106,9 @@ func (api *API) tasksCreate(rw http.ResponseWriter, r *http.Request) {
return
}

taskName, err := api.generateTaskName(ctx, req.Prompt, req.Name)
taskName, err := taskname.Generate(ctx, req.Prompt, req.Name)
if err != nil {
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
Message: "Internal error generating name for task.",
Detail: err.Error(),
})
return
api.Logger.Error(ctx, "unable to generate task name", slog.Error(err))
}

if taskName == "" {
Expand Down
13 changes: 1 addition & 12 deletions coderd/coderd.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,6 @@ import (
"sync/atomic"
"time"

"github.com/anthropics/anthropic-sdk-go"

"github.com/coder/coder/v2/coderd/oauth2provider"
"github.com/coder/coder/v2/coderd/pproflabel"
"github.com/coder/coder/v2/coderd/prebuilds"
Expand Down Expand Up @@ -278,8 +276,6 @@ type Options struct {

// WebPushDispatcher is a way to send notifications over Web Push.
WebPushDispatcher webpush.Dispatcher

AnthropicClient *atomic.Pointer[anthropic.Client]
}

// @title Coder API
Expand Down Expand Up @@ -479,10 +475,6 @@ func New(options *Options) *API {
options.NotificationsEnqueuer = notifications.NewNoopEnqueuer()
}

if options.AnthropicClient == nil {
options.AnthropicClient = &atomic.Pointer[anthropic.Client]{}
}

r := chi.NewRouter()
// We add this middleware early, to make sure that authorization checks made
// by other middleware get recorded.
Expand Down Expand Up @@ -608,8 +600,7 @@ func New(options *Options) *API {
options.Database,
options.Pubsub,
),
dbRolluper: options.DatabaseRolluper,
anthropicClient: options.AnthropicClient,
dbRolluper: options.DatabaseRolluper,
}
api.WorkspaceAppsProvider = workspaceapps.NewDBTokenProvider(
options.Logger.Named("workspaceapps"),
Expand Down Expand Up @@ -1732,8 +1723,6 @@ type API struct {
// dbRolluper rolls up template usage stats from raw agent and app
// stats. This is used to provide insights in the WebUI.
dbRolluper *dbrollup.Rolluper

anthropicClient *atomic.Pointer[anthropic.Client]
}

// Close waits for all WebSocket connections to drain before returning.
Expand Down
86 changes: 86 additions & 0 deletions coderd/taskname/taskname.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package taskname

import (
"context"
"io"

"github.com/anthropics/anthropic-sdk-go"
"github.com/coder/aisdk-go"
"github.com/coder/coder/v2/codersdk"
"golang.org/x/xerrors"
)

const systemPrompt = `Generate a short workspace name from this AI task prompt.

Requirements:
- Only lowercase letters, numbers, and hyphens
- Start with "task-"
- Maximum 32 characters total
- Descriptive of the main task

Examples:
- "Help me debug a Python script" → "task-python-debug"
- "Create a React dashboard component" → "task-react-dashboard"
- "Analyze sales data from Q3" → "task-analyze-q3-sales"
- "Set up CI/CD pipeline" → "task-setup-cicd"

If you cannot create a suitable name, respond with just "task-workspace".`

func Generate(ctx context.Context, prompt, fallback string) (string, error) {
conversation := []aisdk.Message{
{
Role: "system",
Parts: []aisdk.Part{{
Type: aisdk.PartTypeText,
Text: systemPrompt,
}},
},
{
Role: "user",
Parts: []aisdk.Part{{
Type: aisdk.PartTypeText,
Text: prompt,
}},
},
}

anthropicClient := anthropic.NewClient(anthropic.DefaultClientOptions()...)

stream, err := anthropicDataStream(ctx, anthropicClient, conversation)
if err != nil {
return fallback, xerrors.Errorf("create anthropic data stream: %w", err)
}

var acc aisdk.DataStreamAccumulator
stream = stream.WithAccumulator(&acc)

if err := stream.Pipe(io.Discard); err != nil {
return fallback, xerrors.Errorf("pipe data stream")
}

if len(acc.Messages()) == 0 {
return fallback, nil
}

generatedName := acc.Messages()[0].Content

if err := codersdk.NameValid(generatedName); err != nil {
return fallback, xerrors.Errorf("generated name %p not valid: %w", generatedName, err)
}

return generatedName, nil
}

func anthropicDataStream(ctx context.Context, client anthropic.Client, input []aisdk.Message) (aisdk.DataStream, error) {
messages, system, err := aisdk.MessagesToAnthropic(input)
if err != nil {
return nil, xerrors.Errorf("convert messages to anthropic format: %w", err)
}

return aisdk.AnthropicToDataStream(client.Messages.NewStreaming(ctx, anthropic.MessageNewParams{
Model: anthropic.ModelClaude3_5HaikuLatest,
MaxTokens: 24,
System: system,
Messages: messages,
})), nil
}
8 changes: 0 additions & 8 deletions codersdk/deployment.go
Original file line number Diff line number Diff line change
Expand Up @@ -497,7 +497,6 @@ type DeploymentValues struct {
WorkspaceHostnameSuffix serpent.String `json:"workspace_hostname_suffix,omitempty" typescript:",notnull"`
Prebuilds PrebuildsConfig `json:"workspace_prebuilds,omitempty" typescript:",notnull"`
HideAITasks serpent.Bool `json:"hide_ai_tasks,omitempty" typescript:",notnull"`
AnthropicAPIKey serpent.String `json:"anthropic_api_key,omitempty" typescript:",notnull"`

Config serpent.YAMLConfigPath `json:"config,omitempty" typescript:",notnull"`
WriteConfig serpent.Bool `json:"write_config,omitempty" typescript:",notnull"`
Expand Down Expand Up @@ -3206,13 +3205,6 @@ Write out the current server config as YAML to stdout.`,
Group: &deploymentGroupClient,
YAML: "hideAITasks",
},
{
Name: "Anthropic API Key",
Description: "API Key for accessing Anthropic's API platform.",
Env: "ANTHROPIC_API_KEY",
Value: &c.AnthropicAPIKey,
Group: &deploymentGroupClient,
},
}

return opts
Expand Down