feat(tools): add generate_video tool via MiniMax video generation
internal/tools/minimax wraps MiniMax's v2/video_generation (submit)
and v2/query/video_generation/{id} (poll) endpoints. Generation is
asynchronous on MiniMax's side but archie's tool subsystem has no
async-tool flow control (ToolEntry.IsAsync carries no flow control
today), so GenerateAndWait blocks the calling goroutine -- a tool
call, not the model's own generating goroutine -- submitting and
polling until the job reaches a terminal status or MaxWait elapses.
The poll loop tracks elapsed time purely from its injected Sleep
calls rather than a real time.Now() deadline, so a test that fakes
Sleep as an instant counter also makes the loop terminate instantly
instead of spinning in real wall-clock time.
Text-to-video only for now; image-to-video (image_url content items)
is a schema-and-routing change this can grow into. The tool returns a
tools.MultimodalResult carrying the video as a URLs entry -- the
shared envelope the gateway wiring downstream turns into a delivered
attachment.
This commit is contained in:
1 parent
15b6ae5b39
commit
e6954bdbd1
4 files changed
+744
No files matched your search
@@ -0,0 +1,299 @@
|
||||
// Package minimax generates video through MiniMax's video-generation API:
|
||||
// https://platform.minimax.io/docs/api-reference/video-generation-v2-create
|
||||
//
|
||||
// Generation is asynchronous on MiniMax's side (submit a job, poll for a
|
||||
// result), but archied's tool subsystem has no async-tool flow control (see
|
||||
// tools.ToolEntry.IsAsync's doc comment), so GenerateAndWait blocks the
|
||||
// calling goroutine -- a tool call, not the model's own generating
|
||||
// goroutine -- submitting and polling until the job reaches a terminal
|
||||
// status or MaxWait elapses.
|
||||
package minimax
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
// defaultBaseURL is MiniMax's production API host. Overridable for
|
||||
// tests and for an operator pointed at a proxy.
|
||||
defaultBaseURL = "https://api.minimax.io"
|
||||
|
||||
// defaultModel is the only model documented for this endpoint.
|
||||
defaultModel = "MiniMax-H3"
|
||||
|
||||
// defaultResolution and defaultDuration match the middle of MiniMax's
|
||||
// documented ranges (768P/2K; 4-15s) rather than the extremes, so an
|
||||
// unconfigured request is neither the cheapest-lowest-quality nor the
|
||||
// most expensive option by default.
|
||||
defaultResolution = "768P"
|
||||
defaultDuration = 6
|
||||
|
||||
// defaultPollInterval and defaultMaxWait bound one generation. MiniMax
|
||||
// documents no expected completion time, so these are a starting
|
||||
// guess: frequent enough to feel responsive, bounded low enough that
|
||||
// a stuck job fails a chat turn in minutes rather than hanging it.
|
||||
defaultPollInterval = 5 * time.Second
|
||||
defaultMaxWait = 5 * time.Minute
|
||||
|
||||
// defaultTimeout bounds one HTTP call (create or a single query), not
|
||||
// the whole generate-and-wait loop -- that is MaxWait.
|
||||
defaultTimeout = 30 * time.Second
|
||||
)
|
||||
|
||||
// Config controls the client. The zero value is disabled.
|
||||
type Config struct {
|
||||
// Enabled advertises the tool. When false, Tool returns nil.
|
||||
Enabled bool
|
||||
|
||||
// APIKey authenticates every request as a Bearer token.
|
||||
APIKey string
|
||||
|
||||
// BaseURL overrides the API host. Empty uses defaultBaseURL.
|
||||
BaseURL string
|
||||
|
||||
// Timeout bounds one HTTP call. Zero uses defaultTimeout.
|
||||
Timeout time.Duration
|
||||
|
||||
// PollInterval is the delay between status queries. Zero uses
|
||||
// defaultPollInterval.
|
||||
PollInterval time.Duration
|
||||
|
||||
// MaxWait bounds the whole submit-and-poll loop. Zero uses
|
||||
// defaultMaxWait.
|
||||
MaxWait time.Duration
|
||||
|
||||
// Sleep delays between polls. Nil uses time.Sleep. Tests inject a
|
||||
// no-op or counting stand-in so a poll loop that spans MaxWait does
|
||||
// not actually take that long to run.
|
||||
Sleep func(time.Duration)
|
||||
}
|
||||
|
||||
// Client generates video through the MiniMax API.
|
||||
type Client struct {
|
||||
cfg Config
|
||||
http *http.Client
|
||||
}
|
||||
|
||||
// New builds a Client, filling unset Config fields with their defaults.
|
||||
func New(cfg Config) *Client {
|
||||
if cfg.BaseURL == "" {
|
||||
cfg.BaseURL = defaultBaseURL
|
||||
}
|
||||
if cfg.Timeout <= 0 {
|
||||
cfg.Timeout = defaultTimeout
|
||||
}
|
||||
if cfg.PollInterval <= 0 {
|
||||
cfg.PollInterval = defaultPollInterval
|
||||
}
|
||||
if cfg.MaxWait <= 0 {
|
||||
cfg.MaxWait = defaultMaxWait
|
||||
}
|
||||
if cfg.Sleep == nil {
|
||||
cfg.Sleep = time.Sleep
|
||||
}
|
||||
return &Client{cfg: cfg, http: &http.Client{Timeout: cfg.Timeout}}
|
||||
}
|
||||
|
||||
// GenerateRequest is one text-to-video job. Image-to-video (image_url
|
||||
// content items) is not implemented: the first consumer is text-only
|
||||
// generation, and adding image references is a schema-and-routing change
|
||||
// this can grow into rather than needing up front.
|
||||
type GenerateRequest struct {
|
||||
// Prompt is the required text description (MiniMax caps this at 7000
|
||||
// characters; that is not separately enforced here, the API rejects
|
||||
// an oversized prompt with a 400 the caller sees).
|
||||
Prompt string
|
||||
|
||||
// Resolution is "768P" or "2K". Empty uses defaultResolution.
|
||||
Resolution string
|
||||
|
||||
// Duration is the clip length in seconds, 4-15. Zero uses
|
||||
// defaultDuration.
|
||||
Duration int
|
||||
|
||||
// Ratio is the aspect ratio (see the package doc's API reference for
|
||||
// the allowed set). Empty uses "adaptive", MiniMax's own default.
|
||||
Ratio string
|
||||
}
|
||||
|
||||
// GenerateAndWait submits req and blocks until MiniMax reports a terminal
|
||||
// status, returning the hosted video URL on success.
|
||||
func (c *Client) GenerateAndWait(ctx context.Context, req GenerateRequest) (string, error) {
|
||||
taskID, err := c.create(ctx, req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// elapsed is tracked from the injected Sleep calls rather than a real
|
||||
// time.Now() deadline, so a test that fakes Sleep as an instant
|
||||
// counter also makes this loop terminate instantly instead of
|
||||
// spinning in real wall-clock time until an unfaked clock catches up.
|
||||
var elapsed time.Duration
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return "", fmt.Errorf("minimax: task %s: %w", taskID, err)
|
||||
}
|
||||
|
||||
task, err := c.query(ctx, taskID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
switch task.Status {
|
||||
case "succeeded":
|
||||
if task.Content.URL == "" {
|
||||
return "", fmt.Errorf("minimax: task %s succeeded but reported no video url", taskID)
|
||||
}
|
||||
return task.Content.URL, nil
|
||||
case "failed", "cancelled":
|
||||
return "", fmt.Errorf("minimax: task %s %s: %s", taskID, task.Status, task.errorMessage())
|
||||
}
|
||||
|
||||
if elapsed >= c.cfg.MaxWait {
|
||||
return "", fmt.Errorf("minimax: task %s timed out after %v waiting for completion (last status %q)",
|
||||
taskID, c.cfg.MaxWait, task.Status)
|
||||
}
|
||||
c.cfg.Sleep(c.cfg.PollInterval)
|
||||
elapsed += c.cfg.PollInterval
|
||||
}
|
||||
}
|
||||
|
||||
type createResponse struct {
|
||||
TaskID string `json:"task_id"`
|
||||
}
|
||||
|
||||
// create submits req and returns the task ID MiniMax assigned.
|
||||
func (c *Client) create(ctx context.Context, req GenerateRequest) (string, error) {
|
||||
resolution := req.Resolution
|
||||
if resolution == "" {
|
||||
resolution = defaultResolution
|
||||
}
|
||||
duration := req.Duration
|
||||
if duration == 0 {
|
||||
duration = defaultDuration
|
||||
}
|
||||
ratio := req.Ratio
|
||||
if ratio == "" {
|
||||
ratio = "adaptive"
|
||||
}
|
||||
|
||||
body := map[string]any{
|
||||
"model": defaultModel,
|
||||
"resolution": resolution,
|
||||
"duration": duration,
|
||||
"ratio": ratio,
|
||||
"content": []map[string]string{
|
||||
{"type": "text", "text": req.Prompt},
|
||||
},
|
||||
}
|
||||
|
||||
var out createResponse
|
||||
if err := c.doJSON(ctx, http.MethodPost, "/v2/video_generation", body, &out); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if out.TaskID == "" {
|
||||
return "", errors.New("minimax: create response carried no task_id")
|
||||
}
|
||||
return out.TaskID, nil
|
||||
}
|
||||
|
||||
// taskStatus is the polled state of one generation job.
|
||||
type taskStatus struct {
|
||||
Status string `json:"status"`
|
||||
Error *struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
} `json:"error,omitempty"`
|
||||
Content struct {
|
||||
URL string `json:"url"`
|
||||
} `json:"content"`
|
||||
}
|
||||
|
||||
// errorMessage reports the platform's own failure detail, falling back to
|
||||
// a placeholder when MiniMax reported a terminal failure with no error
|
||||
// object -- which the docs don't rule out.
|
||||
func (t taskStatus) errorMessage() string {
|
||||
if t.Error == nil || t.Error.Message == "" {
|
||||
return "no error detail reported"
|
||||
}
|
||||
return t.Error.Message
|
||||
}
|
||||
|
||||
type queryResponse struct {
|
||||
Task taskStatus `json:"task"`
|
||||
}
|
||||
|
||||
// query fetches the current status of taskID.
|
||||
func (c *Client) query(ctx context.Context, taskID string) (taskStatus, error) {
|
||||
var out queryResponse
|
||||
path := "/v2/query/video_generation/" + taskID
|
||||
if err := c.doJSON(ctx, http.MethodGet, path, nil, &out); err != nil {
|
||||
return taskStatus{}, err
|
||||
}
|
||||
return out.Task, nil
|
||||
}
|
||||
|
||||
// apiError is the documented error envelope MiniMax returns on a non-200
|
||||
// response.
|
||||
type apiError struct {
|
||||
Error struct {
|
||||
Type string `json:"type"`
|
||||
Message string `json:"message"`
|
||||
} `json:"error"`
|
||||
}
|
||||
|
||||
// doJSON issues one request and decodes a 200 response into out. A non-200
|
||||
// response is parsed as apiError and returned as an error carrying
|
||||
// MiniMax's own message, so a create/query failure is never reported as a
|
||||
// bare HTTP status.
|
||||
func (c *Client) doJSON(ctx context.Context, method, path string, body, out any) error {
|
||||
var reader io.Reader
|
||||
if body != nil {
|
||||
data, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("minimax: encode request: %w", err)
|
||||
}
|
||||
reader = bytes.NewReader(data)
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, method, strings.TrimRight(c.cfg.BaseURL, "/")+path, reader)
|
||||
if err != nil {
|
||||
return fmt.Errorf("minimax: build request: %w", err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+c.cfg.APIKey)
|
||||
if body != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("minimax: request failed: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
data, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("minimax: read response: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
var apiErr apiError
|
||||
if err := json.Unmarshal(data, &apiErr); err == nil && apiErr.Error.Message != "" {
|
||||
return fmt.Errorf("minimax: %s (http %d)", apiErr.Error.Message, resp.StatusCode)
|
||||
}
|
||||
return fmt.Errorf("minimax: request failed with http %d: %s", resp.StatusCode, string(data))
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(data, out); err != nil {
|
||||
return fmt.Errorf("minimax: decode response: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
package minimax
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// fakeAPI serves a MiniMax API double. create answers with taskID (or
|
||||
// createStatus/createBody when set); each call to query pops the next
|
||||
// entry from queryResponses, repeating the last one once exhausted.
|
||||
type fakeAPI struct {
|
||||
t *testing.T
|
||||
createStatus int
|
||||
createBody string
|
||||
taskID string
|
||||
queryResponses []string
|
||||
queryCalls int
|
||||
lastAuth string
|
||||
lastCreateBody map[string]any
|
||||
}
|
||||
|
||||
func (f *fakeAPI) server() *httptest.Server {
|
||||
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
f.lastAuth = r.Header.Get("Authorization")
|
||||
switch {
|
||||
case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/v2/video_generation"):
|
||||
var body map[string]any
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
f.t.Fatalf("decode create body: %v", err)
|
||||
}
|
||||
f.lastCreateBody = body
|
||||
|
||||
if f.createStatus != 0 && f.createStatus != http.StatusOK {
|
||||
w.WriteHeader(f.createStatus)
|
||||
_, _ = w.Write([]byte(f.createBody))
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte(`{"task_id":"` + f.taskID + `"}`))
|
||||
|
||||
case r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/v2/query/video_generation/"):
|
||||
idx := f.queryCalls
|
||||
if idx >= len(f.queryResponses) {
|
||||
idx = len(f.queryResponses) - 1
|
||||
}
|
||||
f.queryCalls++
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte(f.queryResponses[idx]))
|
||||
|
||||
default:
|
||||
f.t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
func newTestClient(t *testing.T, api *fakeAPI, pollInterval time.Duration) *Client {
|
||||
t.Helper()
|
||||
srv := api.server()
|
||||
t.Cleanup(srv.Close)
|
||||
var slept []time.Duration
|
||||
return New(Config{
|
||||
Enabled: true,
|
||||
APIKey: "test-key",
|
||||
BaseURL: srv.URL,
|
||||
Timeout: 5 * time.Second,
|
||||
PollInterval: pollInterval,
|
||||
// Large relative to any pollInterval used in these tests (including
|
||||
// the 5s default when pollInterval is 0): Sleep is faked, so this
|
||||
// costs nothing in real time and just has to outlast however many
|
||||
// polls a test's queryResponses table needs.
|
||||
MaxWait: 24 * time.Hour,
|
||||
Sleep: func(d time.Duration) { slept = append(slept, d) },
|
||||
})
|
||||
}
|
||||
|
||||
// A submitted job must carry the bearer key and the prompt, and once
|
||||
// MiniMax reports success the client must hand back the hosted URL, not
|
||||
// just the fact that it succeeded.
|
||||
func TestGenerateAndWaitReturnsURLOnSuccess(t *testing.T) {
|
||||
api := &fakeAPI{t: t, taskID: "task-1", queryResponses: []string{
|
||||
`{"task":{"id":"task-1","status":"succeeded","content":{"url":"https://cdn.example.com/v.mp4"}}}`,
|
||||
}}
|
||||
client := newTestClient(t, api, 0)
|
||||
|
||||
url, err := client.GenerateAndWait(context.Background(), GenerateRequest{Prompt: "a cat on a skateboard"})
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateAndWait: %v", err)
|
||||
}
|
||||
if url != "https://cdn.example.com/v.mp4" {
|
||||
t.Errorf("url = %q, want the succeeded task's content url", url)
|
||||
}
|
||||
if api.lastAuth != "Bearer test-key" {
|
||||
t.Errorf("Authorization = %q, want Bearer test-key", api.lastAuth)
|
||||
}
|
||||
if api.lastCreateBody["content"] == nil {
|
||||
t.Fatal("create body carried no content")
|
||||
}
|
||||
}
|
||||
|
||||
// A job that starts queued and moves through running before succeeding
|
||||
// must be polled repeatedly, not just once.
|
||||
func TestGenerateAndWaitPollsUntilTerminal(t *testing.T) {
|
||||
api := &fakeAPI{t: t, taskID: "task-1", queryResponses: []string{
|
||||
`{"task":{"id":"task-1","status":"queued"}}`,
|
||||
`{"task":{"id":"task-1","status":"running"}}`,
|
||||
`{"task":{"id":"task-1","status":"succeeded","content":{"url":"https://cdn.example.com/v.mp4"}}}`,
|
||||
}}
|
||||
client := newTestClient(t, api, 0)
|
||||
|
||||
url, err := client.GenerateAndWait(context.Background(), GenerateRequest{Prompt: "a cat on a skateboard"})
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateAndWait: %v", err)
|
||||
}
|
||||
if url != "https://cdn.example.com/v.mp4" {
|
||||
t.Errorf("url = %q", url)
|
||||
}
|
||||
if api.queryCalls != 3 {
|
||||
t.Errorf("query calls = %d, want 3 (queued, running, succeeded)", api.queryCalls)
|
||||
}
|
||||
}
|
||||
|
||||
// A failed generation must surface the platform's own error message, not
|
||||
// just "it failed" -- the model needs enough detail to tell the user
|
||||
// something useful about why.
|
||||
func TestGenerateAndWaitReturnsErrorOnFailedStatus(t *testing.T) {
|
||||
api := &fakeAPI{t: t, taskID: "task-1", queryResponses: []string{
|
||||
`{"task":{"id":"task-1","status":"failed","error":{"code":"content_policy","message":"prompt rejected"}}}`,
|
||||
}}
|
||||
client := newTestClient(t, api, 0)
|
||||
|
||||
_, err := client.GenerateAndWait(context.Background(), GenerateRequest{Prompt: "a cat on a skateboard"})
|
||||
if err == nil {
|
||||
t.Fatal("expected an error for a failed task")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "prompt rejected") {
|
||||
t.Errorf("error = %v, want it to contain the platform's message", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A create call that MiniMax itself rejects (bad request, auth, quota,
|
||||
// content policy, rate limit) must fail before any polling starts, with
|
||||
// the platform's own description rather than a generic HTTP error.
|
||||
func TestGenerateReportsCreateFailures(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
status int
|
||||
body string
|
||||
wantSubstr string
|
||||
}{
|
||||
{
|
||||
name: "auth",
|
||||
status: http.StatusUnauthorized,
|
||||
body: `{"type":"error","error":{"type":"auth_error","message":"invalid API key","http_code":"401"},"request_id":"r1"}`,
|
||||
wantSubstr: "invalid API key",
|
||||
},
|
||||
{
|
||||
name: "insufficient balance",
|
||||
status: http.StatusPaymentRequired,
|
||||
body: `{"type":"error","error":{"type":"balance_error","message":"insufficient balance","http_code":"402"},"request_id":"r2"}`,
|
||||
wantSubstr: "insufficient balance",
|
||||
},
|
||||
{
|
||||
name: "rate limited",
|
||||
status: http.StatusTooManyRequests,
|
||||
body: `{"type":"error","error":{"type":"rate_limit","message":"too many requests","http_code":"429"},"request_id":"r3"}`,
|
||||
wantSubstr: "too many requests",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
api := &fakeAPI{t: t, createStatus: tt.status, createBody: tt.body}
|
||||
client := newTestClient(t, api, 0)
|
||||
|
||||
_, err := client.GenerateAndWait(context.Background(), GenerateRequest{Prompt: "a cat"})
|
||||
if err == nil {
|
||||
t.Fatal("expected an error")
|
||||
}
|
||||
if !strings.Contains(err.Error(), tt.wantSubstr) {
|
||||
t.Errorf("error = %v, want it to contain %q", err, tt.wantSubstr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A job that never reaches a terminal status must not poll forever: it has
|
||||
// to give up once MaxWait elapses and say so, rather than hanging the tool
|
||||
// call (and the whole turn) indefinitely.
|
||||
func TestGenerateAndWaitTimesOutWithoutRealSleep(t *testing.T) {
|
||||
responses := make([]string, 100)
|
||||
for i := range responses {
|
||||
responses[i] = `{"task":{"id":"task-1","status":"running"}}`
|
||||
}
|
||||
api := &fakeAPI{t: t, taskID: "task-1", queryResponses: responses}
|
||||
|
||||
srv := api.server()
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
elapsed := time.Duration(0)
|
||||
client := New(Config{
|
||||
Enabled: true,
|
||||
APIKey: "test-key",
|
||||
BaseURL: srv.URL,
|
||||
Timeout: 5 * time.Second,
|
||||
PollInterval: time.Second,
|
||||
MaxWait: 10 * time.Second,
|
||||
Sleep: func(d time.Duration) { elapsed += d },
|
||||
})
|
||||
|
||||
start := time.Now()
|
||||
_, err := client.GenerateAndWait(context.Background(), GenerateRequest{Prompt: "a cat"})
|
||||
wallClock := time.Since(start)
|
||||
|
||||
if err == nil {
|
||||
t.Fatal("expected a timeout error")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "timed out") {
|
||||
t.Errorf("error = %v, want a timeout error", err)
|
||||
}
|
||||
if wallClock > time.Second {
|
||||
t.Fatalf("test took %v of real wall-clock time; Sleep was not honored as the delay source", wallClock)
|
||||
}
|
||||
if elapsed < 10*time.Second {
|
||||
t.Errorf("simulated elapsed = %v, want at least MaxWait (10s)", elapsed)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package minimax
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
)
|
||||
|
||||
// ToolName is the registry name of the video-generation tool.
|
||||
const ToolName = "generate_video"
|
||||
|
||||
// Tool builds the registry entry for cfg, or nil when disabled -- the
|
||||
// same "withdraw entirely rather than advertise a broken capability"
|
||||
// reasoning webfetch.Tool documents.
|
||||
//
|
||||
// Classified ClassMutating, not RequiresApproval: it creates a hosted
|
||||
// resource and spends real API credits, which is a mutating action, but
|
||||
// gating every call behind human approval would make the tool unusable
|
||||
// for its purpose. Revisit if usage shows this needs a spend guard.
|
||||
func Tool(cfg Config) *tools.ToolEntry {
|
||||
if !cfg.Enabled {
|
||||
return nil
|
||||
}
|
||||
|
||||
client := New(cfg)
|
||||
|
||||
return &tools.ToolEntry{
|
||||
Name: ToolName,
|
||||
Toolset: "media",
|
||||
Description: "Generate a short video from a text prompt using MiniMax. " +
|
||||
"Generation runs synchronously and can take several minutes; the call " +
|
||||
"blocks until the video is ready or generation fails. Returns a hosted " +
|
||||
"URL for the finished video.",
|
||||
Classification: tools.ClassMutating,
|
||||
Schema: tools.JSONSchema{
|
||||
"type": "object",
|
||||
"properties": map[string]any{
|
||||
"prompt": map[string]any{
|
||||
"type": "string",
|
||||
"description": "Description of the video to generate. Up to 7000 characters.",
|
||||
},
|
||||
"resolution": map[string]any{
|
||||
"type": "string",
|
||||
"enum": []any{"768P", "2K"},
|
||||
"description": "Video resolution. Defaults to 768P.",
|
||||
},
|
||||
"duration": map[string]any{
|
||||
"type": "integer",
|
||||
"minimum": 4,
|
||||
"maximum": 15,
|
||||
"description": "Clip length in seconds, 4-15. Defaults to 6.",
|
||||
},
|
||||
"ratio": map[string]any{
|
||||
"type": "string",
|
||||
"enum": []any{"adaptive", "21:9", "16:9", "4:3", "1:1", "3:4", "9:16"},
|
||||
"description": "Aspect ratio. Defaults to adaptive.",
|
||||
},
|
||||
},
|
||||
"required": []any{"prompt"},
|
||||
},
|
||||
Handler: func(ctx context.Context, input map[string]any) (any, error) {
|
||||
prompt, _ := input["prompt"].(string)
|
||||
if strings.TrimSpace(prompt) == "" {
|
||||
return nil, fmt.Errorf("%s: prompt is required", ToolName)
|
||||
}
|
||||
resolution, _ := input["resolution"].(string)
|
||||
ratio, _ := input["ratio"].(string)
|
||||
duration := 0
|
||||
if d, ok := input["duration"].(float64); ok {
|
||||
duration = int(d)
|
||||
}
|
||||
|
||||
url, err := client.GenerateAndWait(ctx, GenerateRequest{
|
||||
Prompt: prompt,
|
||||
Resolution: resolution,
|
||||
Duration: duration,
|
||||
Ratio: ratio,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", ToolName, err)
|
||||
}
|
||||
|
||||
return tools.MultimodalResult{
|
||||
IsMultimodal: true,
|
||||
Summary: "Generated a video from the prompt.",
|
||||
URLs: []tools.MediaRef{{Type: "video", URL: url}},
|
||||
}, nil
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package minimax
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
)
|
||||
|
||||
// Disabled must withdraw the tool entirely: an advertised tool that always
|
||||
// fails costs the model a wasted round trip to discover it doesn't work,
|
||||
// the same reasoning webfetch.Tool documents for its own Enabled check.
|
||||
func TestToolReturnsNilWhenDisabled(t *testing.T) {
|
||||
if entry := Tool(Config{Enabled: false}); entry != nil {
|
||||
t.Fatal("expected a nil entry when disabled")
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolHasRequiredPromptSchema(t *testing.T) {
|
||||
entry := Tool(Config{Enabled: true, APIKey: "k"})
|
||||
if entry == nil {
|
||||
t.Fatal("expected a non-nil entry")
|
||||
}
|
||||
if entry.Name != ToolName {
|
||||
t.Errorf("Name = %q, want %q", entry.Name, ToolName)
|
||||
}
|
||||
required, _ := entry.Schema["required"].([]any)
|
||||
if len(required) != 1 || required[0] != "prompt" {
|
||||
t.Errorf("required = %v, want [prompt]", required)
|
||||
}
|
||||
}
|
||||
|
||||
// A missing prompt must be rejected before any network call, matching
|
||||
// webfetch's own required-field check.
|
||||
func TestToolHandlerRejectsEmptyPrompt(t *testing.T) {
|
||||
entry := Tool(Config{Enabled: true, APIKey: "k"})
|
||||
if _, err := entry.Handler(context.Background(), map[string]any{}); err == nil {
|
||||
t.Fatal("expected an error for a missing prompt")
|
||||
}
|
||||
}
|
||||
|
||||
// The handler's success path must produce a tools.MultimodalResult carrying
|
||||
// the video as a URLs entry: that is the shared envelope the gateway wiring
|
||||
// (cmd/archied) knows how to turn into a delivered attachment. Returning a
|
||||
// bare string here would leave the video undeliverable no matter how good
|
||||
// the rest of the pipeline is.
|
||||
func TestToolHandlerReturnsMultimodalResultOnSuccess(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch r.Method {
|
||||
case http.MethodPost:
|
||||
_, _ = w.Write([]byte(`{"task_id":"task-1"}`))
|
||||
default:
|
||||
_, _ = w.Write([]byte(`{"task":{"id":"task-1","status":"succeeded","content":{"url":"https://cdn.example.com/v.mp4"}}}`))
|
||||
}
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
entry := Tool(Config{
|
||||
Enabled: true,
|
||||
APIKey: "k",
|
||||
BaseURL: srv.URL,
|
||||
Timeout: 5 * time.Second,
|
||||
PollInterval: 0,
|
||||
MaxWait: time.Hour,
|
||||
Sleep: func(time.Duration) {},
|
||||
})
|
||||
|
||||
out, err := entry.Handler(context.Background(), map[string]any{"prompt": "a cat on a skateboard"})
|
||||
if err != nil {
|
||||
t.Fatalf("Handler: %v", err)
|
||||
}
|
||||
|
||||
data, err := json.Marshal(out)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal handler output: %v", err)
|
||||
}
|
||||
var result tools.MultimodalResult
|
||||
if err := json.Unmarshal(data, &result); err != nil {
|
||||
t.Fatalf("handler output is not a MultimodalResult: %v", err)
|
||||
}
|
||||
if !result.IsMultimodal {
|
||||
t.Error("expected IsMultimodal = true")
|
||||
}
|
||||
if len(result.URLs) != 1 || result.URLs[0].Type != "video" || result.URLs[0].URL != "https://cdn.example.com/v.mp4" {
|
||||
t.Errorf("URLs = %+v, want [{video https://cdn.example.com/v.mp4}]", result.URLs)
|
||||
}
|
||||
}
|
||||
|
||||
// A generation failure must surface as a handler error, not a
|
||||
// MultimodalResult with no URLs: a silently empty result reads to the
|
||||
// model as "it worked but produced nothing" rather than "it failed."
|
||||
func TestToolHandlerReturnsErrorOnGenerationFailure(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch r.Method {
|
||||
case http.MethodPost:
|
||||
_, _ = w.Write([]byte(`{"task_id":"task-1"}`))
|
||||
default:
|
||||
_, _ = w.Write([]byte(`{"task":{"id":"task-1","status":"failed","error":{"message":"prompt rejected"}}}`))
|
||||
}
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
entry := Tool(Config{
|
||||
Enabled: true,
|
||||
APIKey: "k",
|
||||
BaseURL: srv.URL,
|
||||
Timeout: 5 * time.Second,
|
||||
PollInterval: 0,
|
||||
MaxWait: time.Hour,
|
||||
Sleep: func(time.Duration) {},
|
||||
})
|
||||
|
||||
if _, err := entry.Handler(context.Background(), map[string]any{"prompt": "a cat"}); err == nil {
|
||||
t.Fatal("expected an error")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user