製作語言模型提示詞

您可以透過字串串接來建立語言模型提示詞,但這樣做很難進行功能組合,且難以確保提示詞維持在語言模型的內容視窗(context window)限制內。為克服這些限制,您可以使用 @vscode/prompt-tsx 函式庫。

@vscode/prompt-tsx 函式庫提供以下功能:

  • 基於 TSX 的提示詞渲染:使用 TSX 元件撰寫提示詞,使其更具可讀性與維護性。
  • 基於優先順序的修剪(Pruning):自動修剪提示詞中較不重要的部分,以符合模型的內容視窗大小。
  • 靈活的 Token 管理:使用 flexGrowflexReserveflexBasis 等屬性來共同運用 Token 配額。
  • 工具整合:與 VS Code 的語言模型工具 API 整合。

欲了解所有功能概述及詳細使用說明,請參閱 完整 README

本文介紹了使用該函式庫進行提示詞設計的實作範例。這些範例的完整程式碼可以在 prompt-tsx 儲存庫 中找到。

管理對話記錄中的優先順序

在提示詞中包含對話記錄非常重要,因為它讓使用者能夠針對先前的訊息進行後續提問。然而,由於記錄會隨時間增長,您需要確保其優先順序處理得當。我們發現最合理的優先順序模式通常如下:

  1. 基本提示詞指令
  2. 目前的使用者查詢
  3. 最近幾輪的聊天記錄
  4. 任何支援性資料
  5. 在剩餘空間內盡可能容納的歷史記錄

因此,請將提示詞中的歷史記錄分為兩部分,其中最近的對話輪次優先於一般的上下文資訊。

在此函式庫中,樹狀結構中的每個 TSX 節點都有一個優先順序,概念上類似於 zIndex,數字越高代表優先順序越高。

步驟 1:定義 HistoryMessages 元件

若要列出歷史訊息,請定義一個 HistoryMessages 元件。此範例提供了一個很好的起點,但如果您處理的資料類型較複雜,可能需要對其進行擴充。

此範例使用 PrioritizedList 輔助元件,它會自動為其每個子節點分配遞增或遞減的優先順序。

import {
	UserMessage,
	AssistantMessage,
	PromptElement,
	BasePromptElementProps,
	PrioritizedList,
} from '@vscode/prompt-tsx';
import { ChatContext, ChatRequestTurn, ChatResponseTurn, ChatResponseMarkdownPart } from 'vscode';

interface IHistoryMessagesProps extends BasePromptElementProps {
	history: ChatContext['history'];
}

export class HistoryMessages extends PromptElement<IHistoryMessagesProps> {
	render(): PromptPiece {
		const history: (UserMessage | AssistantMessage)[] = [];
		for (const turn of this.props.history) {
			if (turn instanceof ChatRequestTurn) {
				history.push(<UserMessage>{turn.prompt}</UserMessage>);
			} else if (turn instanceof ChatResponseTurn) {
				history.push(
					<AssistantMessage name={turn.participant}>
						{chatResponseToMarkdown(turn)}
					</AssistantMessage>
				);
			}
		}
		return (
			<PrioritizedList priority={0} descending={false}>
				{history}
			</PrioritizedList>
		);
	}
}

步驟 2:定義 Prompt 元件

接下來,定義一個包含基本指令、使用者查詢以及適當優先順序之歷史訊息的 MyPrompt 元件。優先順序值在同層級節點間有效。請記住,在觸及提示詞中的其他部分之前,您可能希望先修剪歷史記錄中較舊的訊息,因此需要拆分兩個 <HistoryMessages> 元素。

import {
	UserMessage,
	PromptElement,
	BasePromptElementProps,
} from '@vscode/prompt-tsx';

interface IMyPromptProps extends BasePromptElementProps {
	history: ChatContext['history'];
	userQuery: string;
}

export class MyPrompt extends PromptElement<IMyPromptProps> {
	render() {
		return (
			<>
				<UserMessage priority={100}>
					Here are your base instructions. They have the highest priority because you want to make
					sure they're always included!
				</UserMessage>
				{/* Older messages in the history have the lowest priority since they're less relevant */}
				<HistoryMessages history={this.props.history.slice(0, -2)} priority={0} />
				{/* The last 2 history messages are preferred over any workspace context you have below */}
				<HistoryMessages history={this.props.history.slice(-2)} priority={80} />
				{/* The user query is right behind the based instructions in priority */}
				<UserMessage priority={90}>{this.props.userQuery}</UserMessage>
				<UserMessage priority={70}>
					With a slightly lower priority, you can include some contextual data about the workspace
					or files here...
				</UserMessage>
			</>
		);
	}
}

現在,在函式庫嘗試修剪提示詞的其他元素之前,所有較舊的歷史訊息都會先被修剪。

步驟 3:定義 History 元件

為了簡化使用,定義一個包裹歷史訊息的 History 元件,並使用 passPriority 屬性將其作為直通容器(pass-through container)。透過 passPriority,其子節點在優先順序判斷上將被視為容器元素的直接子節點。

import { PromptElement, BasePromptElementProps } from '@vscode/prompt-tsx';

interface IHistoryProps extends BasePromptElementProps {
	history: ChatContext['history'];
	newer: number; // last 2 message priority values
	older: number; // previous message priority values
	passPriority: true; // require this prop be set!
}

export class History extends PromptElement<IHistoryProps> {
	render(): PromptPiece {
		return (
			<>
				<HistoryMessages history={this.props.history.slice(0, -2)} priority={this.props.older} />
				<HistoryMessages history={this.props.history.slice(-2)} priority={this.props.newer} />
			</>
		);
	}
}

現在,您可以重複使用此單一元素來包含聊天記錄。

<History history={this.props.history} passPriority older={0} newer={80}/>

彈性調整檔案內容以符合需求

在此範例中,您希望將使用者目前檢視的所有檔案內容包含在提示詞中。這些檔案可能很大,大到若全部包含會導致內容被修剪!此範例展示如何使用 flexGrow 屬性來共同調整檔案內容大小,使其適應 Token 配額。

步驟 1:定義基本指令與使用者查詢

首先,定義一個包含基本指令的 UserMessage 元件。

<UserMessage priority={100}>Here are your base instructions.</UserMessage>

接著使用 UserMessage 元件包含使用者查詢。此元件具有高優先順序,以確保它緊接在基本指令之後被納入。

<UserMessage priority={90}>{this.props.userQuery}</UserMessage>

步驟 2:包含檔案內容

現在,您可以使用 FileContext 元件包含檔案內容。為其分配一個 flexGrow 值為 1,以確保它在基本指令、使用者查詢和歷史記錄之後渲染。

<FileContext priority={70} flexGrow={1} files={this.props.files} />

透過 flexGrow 值,該元素會獲得在 render()prepare() 呼叫期間傳遞的 PromptSizing 物件中任何「未被使用」的 Token 配額。您可以在 prompt-tsx 文件 中閱讀更多關於彈性元素行為的資訊。

步驟 3:包含歷史記錄

接下來,使用您先前建立的 History 元件包含歷史訊息。這會稍微複雜一些,因為您既希望顯示部分歷史記錄,又希望檔案內容佔用提示詞的大部分空間。

因此,為 History 元件分配 flexGrow 值為 2,以確保它在包括 <FileContext /> 在內的所有其他元素之後渲染。同時,設定 flexReserve 值為 "/5",以便為歷史記錄保留總配額的 1/5。

<History
	history={this.props.history}
	passPriority
	older={0}
	newer={80}
	flexGrow={2}
	flexReserve="/5"
/>

步驟 3:組合提示詞的所有元素

現在,將所有元素組合到 MyPrompt 元件中。

import {
	UserMessage,
	PromptElement,
	BasePromptElementProps,
} from '@vscode/prompt-tsx';
import { History } from './history';

interface IFilesToInclude {
	document: TextDocument;
	line: number;
}

interface IMyPromptProps extends BasePromptElementProps {
	history: ChatContext['history'];
	userQuery: string;
	files: IFilesToInclude[];
}

export class MyPrompt extends PromptElement<IMyPromptProps> {
	render() {
		return (
			<>
				<UserMessage priority={100}>Here are your base instructions.</UserMessage>
				<History
					history={this.props.history}
					passPriority
					older={0}
					newer={80}
					flexGrow={2}
					flexReserve="/5"
				/>
				<UserMessage priority={90}>{this.props.userQuery}</UserMessage>
				<FileContext priority={70} flexGrow={1} files={this.props.files} />
			</>
		);
	}
}

步驟 4:定義 FileContext 元件

最後,定義一個 FileContext 元件,其中包含使用者目前檢視的檔案內容。由於使用了 flexGrow,您可以利用 PromptSizing 中的資訊來實作邏輯,針對每個檔案獲取「感興趣」行周圍盡可能多的行數。

為簡潔起見,getExpandedFiles 的實作邏輯在此省略。您可以查看 prompt-tsx 儲存庫 中的程式碼。

import { PromptElement, BasePromptElementProps, PromptSizing, PromptPiece } from '@vscode/prompt-tsx';

class FileContext extends PromptElement<{ files: IFilesToInclude[] } & BasePromptElementProps> {
	async render(_state: void, sizing: PromptSizing): Promise<PromptPiece> {
		const files = await this.getExpandedFiles(sizing);
		return <>{files.map(f => f.toString())}</>;
	}

	private async getExpandedFiles(sizing: PromptSizing) {
		// Implementation details are summarized here.
		// Refer to the repo for the complete implementation.
	}
}

總結

在這些範例中,您建立了一個 MyPrompt 元件,其中包含基本指令、使用者查詢、歷史訊息以及具有不同優先順序的檔案內容。您使用了 flexGrow 來共同調整檔案內容大小,以符合 Token 配額。

遵循此模式,您可以確保提示詞中最關鍵的部分始終被包含,而較不重要的部分則會根據需要進行修剪,以適應模型的內容視窗。有關 getExpandedFiles 方法和 FileContextTracker 類別的完整實作細節,請參考 prompt-tsx 儲存庫

© . This site is unofficial and not affiliated with Microsoft.