import { AssistantMessage, BasePromptElementProps, Chunk, PrioritizedList, PromptElement, PromptElementProps, PromptMetadata, PromptPiece, PromptReference, PromptSizing, ToolCall, ToolMessage, UserMessage } from '@vscode/prompt-tsx'; import { ToolResult } from '@vscode/prompt-tsx/dist/base/promptElements'; import * as vscode from 'vscode'; import { isTsxToolUserMetadata } from './toolParticipant'; export interface ToolCallRound { response: string; toolCalls: vscode.LanguageModelToolCallPart[]; } export interface ToolUserProps extends BasePromptElementProps { request: vscode.ChatRequest; context: vscode.ChatContext; toolCallRounds: ToolCallRound[]; toolCallResults: Record; } export class ToolUserPrompt extends PromptElement { render(_state: void, _sizing: PromptSizing) { return ( <> Instructions:
- The user will ask a question, or ask you to perform a task, and it may require lots of research to answer correctly. There is a selection of tools that let you perform actions or retrieve helpful context to answer the user's question.
- If you aren't sure which tool is relevant, you can call multiple tools. You can call tools repeatedly to take actions or gather as much context as needed until you have completed the task fully. Don't give up unless you are sure the request cannot be fulfilled with the tools you have.
- Don't make assumptions about the situation- gather context first, then perform the task or answer the question.
- Don't ask the user for confirmation to use tools, just use them.
{this.props.request.prompt} ); } } interface ToolCallsProps extends BasePromptElementProps { toolCallRounds: ToolCallRound[]; toolCallResults: Record; toolInvocationToken: vscode.ChatParticipantToolToken | undefined; } const dummyCancellationToken: vscode.CancellationToken = new vscode.CancellationTokenSource().token; /** * Render a set of tool calls, which look like an AssistantMessage with a set of tool calls followed by the associated UserMessages containing results. */ class ToolCalls extends PromptElement { async render(_state: void, _sizing: PromptSizing) { if (!this.props.toolCallRounds.length) { return undefined; } // Note- for the copilot models, the final prompt must end with a non-tool-result UserMessage return <> {this.props.toolCallRounds.map(round => this.renderOneToolCallRound(round))} Above is the result of calling one or more tools. The user cannot see the results, so you should explain them to the user if referencing them in your answer. ; } private renderOneToolCallRound(round: ToolCallRound) { const assistantToolCalls: ToolCall[] = round.toolCalls.map(tc => ({ type: 'function', function: { name: tc.name, arguments: JSON.stringify(tc.input) }, id: tc.callId })); return ( {round.response} {round.toolCalls.map(toolCall => )} ); } } interface ToolResultElementProps extends BasePromptElementProps { toolCall: vscode.LanguageModelToolCallPart; toolInvocationToken: vscode.ChatParticipantToolToken | undefined; toolCallResult: vscode.LanguageModelToolResult | undefined; } /** * One tool call result, which either comes from the cache or from invoking the tool. */ class ToolResultElement extends PromptElement { async render(state: void, sizing: PromptSizing): Promise { const tool = vscode.lm.tools.find(t => t.name === this.props.toolCall.name); if (!tool) { console.error(`Tool not found: ${this.props.toolCall.name}`); return Tool not found; } const tokenizationOptions: vscode.LanguageModelToolTokenizationOptions = { tokenBudget: sizing.tokenBudget, countTokens: async (content: string) => sizing.countTokens(content), }; const toolResult = this.props.toolCallResult ?? await vscode.lm.invokeTool(this.props.toolCall.name, { input: this.props.toolCall.input, toolInvocationToken: this.props.toolInvocationToken, tokenizationOptions }, dummyCancellationToken); return ( ); } } export class ToolResultMetadata extends PromptMetadata { constructor( public toolCallId: string, public result: vscode.LanguageModelToolResult, ) { super(); } } interface HistoryProps extends BasePromptElementProps { priority: number; context: vscode.ChatContext; } /** * Render the chat history, including previous tool call/results. */ class History extends PromptElement { render(_state: void, _sizing: PromptSizing) { return ( {this.props.context.history.map((message) => { if (message instanceof vscode.ChatRequestTurn) { return ( <> {} {message.prompt} ); } else if (message instanceof vscode.ChatResponseTurn) { const metadata = message.result.metadata; if (isTsxToolUserMetadata(metadata) && metadata.toolCallsMetadata.toolCallRounds.length > 0) { return ; } return {chatResponseToString(message)}; } })} ); } } /** * Convert the stream of chat response parts into something that can be rendered in the prompt. */ function chatResponseToString(response: vscode.ChatResponseTurn): string { return response.response .map((r) => { if (r instanceof vscode.ChatResponseMarkdownPart) { return r.value.value; } else if (r instanceof vscode.ChatResponseAnchorPart) { if (r.value instanceof vscode.Uri) { return r.value.fsPath; } else { return r.value.uri.fsPath; } } return ''; }) .join(''); } interface PromptReferencesProps extends BasePromptElementProps { references: ReadonlyArray; excludeReferences?: boolean; } /** * Render references that were included in the user's request, eg files and selections. */ class PromptReferences extends PromptElement { render(_state: void, _sizing: PromptSizing): PromptPiece { return ( {this.props.references.map(ref => ( ))} ); } } interface PromptReferenceProps extends BasePromptElementProps { ref: vscode.ChatPromptReference; excludeReferences?: boolean; } class PromptReferenceElement extends PromptElement { async render(_state: void, _sizing: PromptSizing): Promise { const value = this.props.ref.value; if (value instanceof vscode.Uri) { const fileContents = (await vscode.workspace.fs.readFile(value)).toString(); return ( {!this.props.excludeReferences && } {value.fsPath}:
```
{fileContents}
```
); } else if (value instanceof vscode.Location) { const rangeText = (await vscode.workspace.openTextDocument(value.uri)).getText(value.range); return ( {!this.props.excludeReferences && } {value.uri.fsPath}:{value.range.start.line + 1}-$
{value.range.end.line + 1}:
```
{rangeText}
```
); } else if (typeof value === 'string') { return {value}; } } } type TagProps = PromptElementProps<{ name: string; }>; class Tag extends PromptElement { private static readonly _regex = /^[a-zA-Z_][\w.-]*$/; render() { const { name } = this.props; if (!Tag._regex.test(name)) { throw new Error(`Invalid tag name: ${this.props.name}`); } return ( <> {'<' + name + '>'}
<> {this.props.children}
{''}
); } }