agent-tool.go

  1package agent
  2
  3import (
  4	"context"
  5	"encoding/json"
  6	"fmt"
  7
  8	"github.com/kujtimiihoxha/termai/internal/llm/tools"
  9	"github.com/kujtimiihoxha/termai/internal/lsp"
 10	"github.com/kujtimiihoxha/termai/internal/message"
 11	"github.com/kujtimiihoxha/termai/internal/session"
 12)
 13
 14type agentTool struct {
 15	sessions   session.Service
 16	messages   message.Service
 17	lspClients map[string]*lsp.Client
 18}
 19
 20const (
 21	AgentToolName = "agent"
 22)
 23
 24type AgentParams struct {
 25	Prompt string `json:"prompt"`
 26}
 27
 28func (b *agentTool) Info() tools.ToolInfo {
 29	return tools.ToolInfo{
 30		Name:        AgentToolName,
 31		Description: "Launch a new agent that has access to the following tools: GlobTool, GrepTool, LS, View. When you are searching for a keyword or file and are not confident that you will find the right match on the first try, use the Agent tool to perform the search for you. For example:\n\n- If you are searching for a keyword like \"config\" or \"logger\", or for questions like \"which file does X?\", the Agent tool is strongly recommended\n- If you want to read a specific file path, use the View or GlobTool tool instead of the Agent tool, to find the match more quickly\n- If you are searching for a specific class definition like \"class Foo\", use the GlobTool tool instead, to find the match more quickly\n\nUsage notes:\n1. Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses\n2. When the agent is done, it will return a single message back to you. The result returned by the agent is not visible to the user. To show the user the result, you should send a text message back to the user with a concise summary of the result.\n3. Each agent invocation is stateless. You will not be able to send additional messages to the agent, nor will the agent be able to communicate with you outside of its final report. Therefore, your prompt should contain a highly detailed task description for the agent to perform autonomously and you should specify exactly what information the agent should return back to you in its final and only message to you.\n4. The agent's outputs should generally be trusted\n5. IMPORTANT: The agent can not use Bash, Replace, Edit, so can not modify files. If you want to use these tools, use them directly instead of going through the agent.",
 32		Parameters: map[string]any{
 33			"prompt": map[string]any{
 34				"type":        "string",
 35				"description": "The task for the agent to perform",
 36			},
 37		},
 38		Required: []string{"prompt"},
 39	}
 40}
 41
 42func (b *agentTool) Run(ctx context.Context, call tools.ToolCall) (tools.ToolResponse, error) {
 43	var params AgentParams
 44	if err := json.Unmarshal([]byte(call.Input), &params); err != nil {
 45		return tools.NewTextErrorResponse(fmt.Sprintf("error parsing parameters: %s", err)), nil
 46	}
 47	if params.Prompt == "" {
 48		return tools.NewTextErrorResponse("prompt is required"), nil
 49	}
 50
 51	sessionID, messageID := tools.GetContextValues(ctx)
 52	if sessionID == "" || messageID == "" {
 53		return tools.NewTextErrorResponse("session ID and message ID are required"), nil
 54	}
 55
 56	agent, err := NewTaskAgent(b.lspClients)
 57	if err != nil {
 58		return tools.NewTextErrorResponse(fmt.Sprintf("error creating agent: %s", err)), nil
 59	}
 60
 61	session, err := b.sessions.CreateTaskSession(ctx, call.ID, sessionID, "New Agent Session")
 62	if err != nil {
 63		return tools.NewTextErrorResponse(fmt.Sprintf("error creating session: %s", err)), nil
 64	}
 65
 66	err = agent.Generate(ctx, session.ID, params.Prompt)
 67	if err != nil {
 68		return tools.NewTextErrorResponse(fmt.Sprintf("error generating agent: %s", err)), nil
 69	}
 70
 71	messages, err := b.messages.List(ctx, session.ID)
 72	if err != nil {
 73		return tools.NewTextErrorResponse(fmt.Sprintf("error listing messages: %s", err)), nil
 74	}
 75	if len(messages) == 0 {
 76		return tools.NewTextErrorResponse("no messages found"), nil
 77	}
 78
 79	response := messages[len(messages)-1]
 80	if response.Role != message.Assistant {
 81		return tools.NewTextErrorResponse("no assistant message found"), nil
 82	}
 83
 84	updatedSession, err := b.sessions.Get(ctx, session.ID)
 85	if err != nil {
 86		return tools.NewTextErrorResponse(fmt.Sprintf("error: %s", err)), nil
 87	}
 88	parentSession, err := b.sessions.Get(ctx, sessionID)
 89	if err != nil {
 90		return tools.NewTextErrorResponse(fmt.Sprintf("error: %s", err)), nil
 91	}
 92
 93	parentSession.Cost += updatedSession.Cost
 94	parentSession.PromptTokens += updatedSession.PromptTokens
 95	parentSession.CompletionTokens += updatedSession.CompletionTokens
 96
 97	_, err = b.sessions.Save(ctx, parentSession)
 98	if err != nil {
 99		return tools.NewTextErrorResponse(fmt.Sprintf("error: %s", err)), nil
100	}
101	return tools.NewTextResponse(response.Content().String()), nil
102}
103
104func NewAgentTool(
105	Sessions session.Service,
106	Messages message.Service,
107) tools.BaseTool {
108	return &agentTool{
109		sessions: Sessions,
110		messages: Messages,
111	}
112}