Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
33 changes: 33 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,39 @@ public class Milks
}
```

### Chat prompts in 0.3 preview

`JsonTranslator<T>` now sends its schema and JSON output instructions as one **system** message.
For a string request it sends exactly one more message: the unmodified **user** text. If you
supply a preamble (including history) or a multi-section `Prompt`, the order is **system,
preamble sections, request sections**. The translator neither joins those sections nor changes
their sources. Only mark application-owned content as `system`; keep retrieved text and prior
turns in their original roles. `ProgramTranslator` includes both the program grammar and the
target API in its system instructions.

On repair, the original prompt is followed by the raw rejected **assistant** response and a
**user** message with the validation diagnostic. A further repair replaces that last pair,
as before. Role separation does not prevent prompt injection, replace validation, or authorize
the execution of a generated program.

**Choosing a prompt builder:**

* For different application instructions, derive from `SchemaFirstJsonTranslatorPrompts` (or
`SchemaFirstProgramTranslatorPrompts`) and override `CreateSystemInstructions(TypeSchema)`.
This hook doesn't receive request or history data.
* An explicitly supplied `IJsonTranslatorPrompts` or translator override still controls the
full request. Its output is used as returned, never wrapped in a new system message. To
retain the previous wrapped layout, including when delegating to the translator's base
implementation, set `translator.Prompts = JsonTranslatorPrompts.Legacy;`. Existing
subclasses of `JsonTranslatorPrompts` retain their full-request base implementation.
For programs use `programTranslator.Prompts = new ProgramTranslatorPrompts(programTranslator.ApiDef);`.
* Use a chat adapter for schema-first translation. Custom `ILanguageModel` implementations
must forward the individual sections, not `prompt.ToString()`. The Semantic Kernel
`TextCompletionModel` can send only a single string: it rejects role-bearing or multi-message
prompts unless the builder explicitly allows flattening. The legacy builders do; for a
hand-built text prompt the opt-in is `prompt.AllowTextFlattening = true`. Textual role
labels (`IncludeSectionSource`) are not model roles.

### Accessing failed output

Failed validator results expose optional `FailureInfo` through `Result<T>.Failure`.
Expand Down
15 changes: 10 additions & 5 deletions examples/Calendar/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,17 @@ namespace Calendar;
public class CalendarApp : ConsoleApp
{
private readonly JsonTranslator<CalendarActions> _translator;
private readonly TimeProvider _clock;

public CalendarApp()
: this(new LanguageModel(Config.LoadOpenAI()), TimeProvider.System)
{
_translator = new JsonTranslator<CalendarActions>(
new LanguageModel(Config.LoadOpenAI())
);
}

public CalendarApp(ILanguageModel model, TimeProvider clock)
{
_translator = new JsonTranslator<CalendarActions>(model);
_clock = clock;

// Uncomment to see ALL raw messages to and from the AI
//base.SubscribeAllEvents(_translator);
Expand All @@ -23,8 +28,8 @@ public CalendarApp()

public override async Task ProcessInputAsync(string input, CancellationToken cancelToken)
{
string request = $"{input}\n{PromptLibrary.Now()}";
CalendarActions actions = await _translator.TranslateAsync(request, cancelToken);
CalendarActions actions = await _translator.TranslateAsync(input,
[PromptLibrary.Now(_clock.GetLocalNow().DateTime)], cancelToken: cancelToken);
Console.WriteLine(Microsoft.TypeChat.Json.Stringify(actions));
PrintUnknown(actions);
}
Expand Down
20 changes: 12 additions & 8 deletions examples/HealthData/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,16 @@ public class HealthDataAgent : ConsoleApp
private readonly AgentWithHistory<HealthDataResponse> _agent;

public HealthDataAgent()
: this(new ChatLanguageModel(Config.LoadOpenAI()), TimeProvider.System)
{
}

public HealthDataAgent(ILanguageModel model, TimeProvider clock)
{
// Create an agent with history
_agent = new AgentWithHistory<HealthDataResponse>(new ChatLanguageModel(Config.LoadOpenAI()));
_agent = new AgentWithHistory<HealthDataResponse>(model);
// Instruct the agent on how it should act
GiveAgentInstructions();
GiveAgentInstructions(clock.GetLocalNow().DateTime);
// We only capture the questions that the model asked us into history
_agent.CreateMessageForHistory = (r) => (r.HasMessage) ? Message.FromAssistant(r.Message) : null;
// Enforce additional constraints validation, as provided by System.ComponentModel.DataAnnotations namespace
Expand All @@ -41,19 +46,19 @@ public override async Task ProcessInputAsync(string input, CancellationToken can
/// <summary>
/// Give the agent instructions
/// </summary>
private void GiveAgentInstructions()
private void GiveAgentInstructions(DateTime now)
{
Prompt instructions = _agent.Instructions;
// Supply current date and time, and how to use it
instructions += PromptLibrary.Now();
instructions += "Help me enter my health data step by step.\n" +
"Ask specific questions to gather required and optional fields I have not already provided" +
instructions += PromptLibrary.Now(now);
instructions.AppendInstruction("Help me enter my health data step by step.\n" +
"Ask specific questions to gather required and optional fields I have not already provided\n" +
"Stop asking if I don't know the answer\n" +
"Automatically fix my spelling mistakes\n" +
"My health data may be complex: always record and return ALL of it.\n" +
"Always return a response:\n" +
"- If you don't understand what I say, ask a question.\n" +
"- At least respond with an OK message.";
"- At least respond with an OK message.");
}

public override Task ProcessCommandAsync(string cmd, IList<string> args)
Expand Down Expand Up @@ -123,4 +128,3 @@ private static void PrintHelp()
Console.WriteLine("@clear: Reset history");
}
}

11 changes: 5 additions & 6 deletions examples/typechat.examplesLib/Classification/TextClassifier.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public TextClassifier(ILanguageModel languageModel)
/// <param name="languageModel">model to use</param>
/// <param name="classes">Classes to classify into</param>
public TextClassifier(ILanguageModel languageModel, TextClasses classes)
: base(languageModel, new TypeValidator<TextClassification>(classes.Vocabs))
: base(languageModel, new TypeValidator<TextClassification>(classes.Vocabs), new ClassifierPrompts(classes))
{
if (classes is null)
{
Expand All @@ -42,11 +42,10 @@ public TextClassifier(ILanguageModel languageModel, TextClasses classes)
/// </summary>
public TextClasses Classes => _classes;

protected override Prompt CreateRequestPrompt(Prompt request, IList<IPromptSection> preamble)
private sealed class ClassifierPrompts(TextClasses classes) : SchemaFirstJsonTranslatorPrompts
{
string classes = Json.Stringify(_classes);
string fullRequest = $"Classify \"{request}\" using the following classification table:\n{classes}\n";
return base.CreateRequestPrompt(fullRequest, preamble);
protected override string CreateSystemInstructions(TypeSchema schema) =>
base.CreateSystemInstructions(schema) +
$"Classify the user request using the following classification table:\n{Json.Stringify(classes)}\n";
}
}

2 changes: 1 addition & 1 deletion examples/typechat.examplesLib/Dialog/Agent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ public async Task<Message> GetResponseMessageAsync(Message requestMessage, Cance
//
// Translate
//
T response = await _translator.TranslateAsync(preparedRequestText, context, null, cancelToken).ConfigureAwait(false);
T response = await _translator.TranslateAsync(new Prompt { preparedRequestMessage }, context, null, cancelToken).ConfigureAwait(false);

Message responseMessage = Message.FromAssistant(response);

Expand Down
12 changes: 7 additions & 5 deletions examples/typechat.examplesLib/PromptLibrary.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,13 @@ public class PromptLibrary
/// Tell the model about the current Date and Time
/// </summary>
/// <returns>prompt section</returns>
public static PromptSection Now()
public static PromptSection Now() => Now(DateTime.Now);

/// <summary>Give relative-date instructions using an application-supplied local time.</summary>
public static PromptSection Now(DateTime now)
{
DateTime now = DateTime.Now;
PromptSection section = $"Use precise date and times RELATIVE TO CURRENT DATE: {now.ToLongDateString()} CURRENT TIME: {now.ToLongTimeString()}\n";
section += "Also turn ranges like next week and next month into precise dates";
return section;
return PromptSection.FromSystem(
$"Use precise date and times RELATIVE TO CURRENT DATE: {now.ToLongDateString()} CURRENT TIME: {now.ToLongTimeString()}\n" +
"Also turn ranges like next week and next month into precise dates");
}
}
5 changes: 5 additions & 0 deletions src/package/NUGET.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,9 @@ TypeChat.NET provides **cross platform** libraries that help you build natural l

# Getting Started

In the 0.3 preview, chat translation puts the application schema and JSON format in a system
message, then preserves preamble and request sections in order. A fresh user request is sent
verbatim. Use a role-aware chat adapter, or explicitly select `JsonTranslatorPrompts.Legacy`
for the previous text layout. See the [prompt migration guide](https://github.com/microsoft/typechat.net#chat-prompts-in-03-preview).

Learn about and get the latest updates on the TypeChat.NET project on the [TypeChat.NET GitHub repository](https://github.com/microsoft/typechat.net).
2 changes: 1 addition & 1 deletion src/package/nuget.props
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<!-- NuGet package properties -->
<PropertyGroup>
<PackageId>$(AssemblyName)</PackageId>
<Version>0.1.0-pre</Version>
<Version>0.3.0-pre</Version>
<IsPackable>true</IsPackable>
<Authors>Microsoft</Authors>
<Company>Microsoft</Company>
Expand Down
2 changes: 1 addition & 1 deletion src/typechat.meai/ChatLanguageModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ public static ChatRole GetRole(this IPromptSection section)
{
return ChatRole.System;
}
return ChatRole.User;
return new ChatRole(source);
}

public static void Append(this List<ChatMessage> history, IEnumerable<IPromptSection> sections)
Expand Down
2 changes: 1 addition & 1 deletion src/typechat.program/ProgramTranslator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ public ProgramTranslator(ILanguageModel model, IJsonTypeValidator<Program> valid
: base(
model,
validator,
new ProgramTranslatorPrompts(apiDef)
new SchemaFirstProgramTranslatorPrompts(apiDef)
)
{
_apiDef = apiDef;
Expand Down
30 changes: 21 additions & 9 deletions src/typechat.program/ProgramTranslatorPrompts.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
namespace Microsoft.TypeChat;

/// <summary>
/// Default Prompts used by the program translator
/// Legacy full-request prompts for a program translator.
/// </summary>
public class ProgramTranslatorPrompts : JsonTranslatorPrompts
{
Expand All @@ -22,17 +22,29 @@ public ProgramTranslatorPrompts(string apiDef)

public override Prompt CreateRequestPrompt(TypeSchema schema, Prompt request, IList<IPromptSection> context)
{
return RequestProgramPrompt(request, schema.Schema.Text, _apiDef, context);
if (IsSingleUserText(request))
{
// The legacy program translator included Prompt.ToString()'s trailing newline.
return RequestProgramPrompt(request[0].GetText() + "\n", schema.Schema.Text, _apiDef, context);
}
return CreateLegacyPrompt(request, schema.Schema.Text, _apiDef, context);
}

public static Prompt RequestProgramPrompt(string request, string programSchema, string apiDef, IList<IPromptSection> context)
{
Prompt prompt = new Prompt();
prompt += "You are a service that translates user requests into programs represented as JSON using the following TypeScript definitions:\n" +
$"```\n{programSchema}```\n" +
"The programs can call functions from the API defined in the following TypeScript definitions:\n" +
$"```\n{apiDef}```\n";
AddContextAndRequest(prompt, request, context);
return prompt;
return CreateLegacyPrompt(request, programSchema, apiDef, context);
}

private static Prompt CreateLegacyPrompt(Prompt request, string programSchema, string apiDef, IList<IPromptSection> context)
{
Prompt prompt = new Prompt { AllowTextFlattening = true };
prompt.Append(ProgramInstructions(programSchema, apiDef));
return AddContextAndRequest(prompt, request, context);
}

internal static string ProgramInstructions(string programSchema, string apiDef) =>
"You are a service that translates user requests into programs represented as JSON using the following TypeScript definitions:\n" +
$"```\n{programSchema}```\n" +
"The programs can call functions from the API defined in the following TypeScript definitions:\n" +
$"```\n{apiDef}```\n";
}
19 changes: 19 additions & 0 deletions src/typechat.program/SchemaFirstProgramTranslatorPrompts.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Copyright (c) Microsoft. All rights reserved.

namespace Microsoft.TypeChat;

/// <summary>Default program prompts: both the program grammar and the target API are system instructions.</summary>
public class SchemaFirstProgramTranslatorPrompts : SchemaFirstJsonTranslatorPrompts
{
private readonly string _apiDef;

public SchemaFirstProgramTranslatorPrompts(string apiDef)
{
ArgumentVerify.ThrowIfNullOrEmpty(apiDef, nameof(apiDef));
_apiDef = apiDef;
}

/// <inheritdoc/>
protected override string CreateSystemInstructions(TypeSchema schema) =>
ProgramTranslatorPrompts.ProgramInstructions(schema.Schema.Text, _apiDef) + JsonFormatInstructions;
}
2 changes: 1 addition & 1 deletion src/typechat.sk/ModelEx.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public static AuthorRole GetRole(this IPromptSection section)
{
return AuthorRole.System;
}
return AuthorRole.User;
return new AuthorRole(source);
}

public static void Append(this ChatHistory history, IEnumerable<IPromptSection> sections)
Expand Down
7 changes: 7 additions & 0 deletions src/typechat.sk/TextCompletionModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,13 @@ public TextCompletionModel(ITextGenerationService service, ModelInfo model)

public async Task<string> CompleteAsync(Prompt prompt, TranslationSettings? settings = null, CancellationToken cancelToken = default)
{
ArgumentVerify.ThrowIfNull(prompt, nameof(prompt));
if (!prompt.AllowTextFlattening && (prompt.Count != 1 || prompt[0].Source != PromptSection.Sources.User))
{
throw new NotSupportedException(
"TextCompletionModel cannot preserve chat roles. Use a chat model, select legacy translator prompts, " +
"or explicitly set Prompt.AllowTextFlattening for a custom text prompt.");
}
OpenAIPromptExecutionSettings? requestSettings = ToRequestSettings(settings);
string request = prompt.ToString(IncludeSectionSource);
var response = await _service.GetTextContentsAsync(request, requestSettings, _kernel, cancelToken).ConfigureAwait(false);
Expand Down
27 changes: 17 additions & 10 deletions src/typechat/JsonTranslatorPrompts.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,20 @@
namespace Microsoft.TypeChat;

/// <summary>
/// The standard prompts used by JsonTranslator
/// You can customize prompts you give to the translator as per your scenario
/// To do so, you can implement IJsonTranslatorPrompts OR just inherit from this class and override
/// The legacy full-request prompts. Supply these explicitly for the old layout, or
/// derive from <see cref="SchemaFirstJsonTranslatorPrompts"/> to customize system instructions.
/// </summary>
public class JsonTranslatorPrompts : IJsonTranslatorPrompts
{
internal static readonly JsonTranslatorPrompts Default = new JsonTranslatorPrompts();
internal static readonly JsonTranslatorPrompts Default = new SchemaFirstJsonTranslatorPrompts();

/// <summary>Opt into the original wrapped request layout, including for text-only models.</summary>
public static JsonTranslatorPrompts Legacy { get; } = new JsonTranslatorPrompts();

public virtual Prompt CreateRequestPrompt(TypeSchema typeSchema, Prompt request, IList<IPromptSection> context = null)
{
ArgumentVerify.ThrowIfNull(request, nameof(request));
Prompt prompt = new Prompt();
Prompt prompt = new Prompt { AllowTextFlattening = true };

prompt += IntroSection(typeSchema.TypeFullName, typeSchema.Schema);
AddContextAndRequest(prompt, request, context);
Expand All @@ -41,7 +43,7 @@ public static Prompt AddContextAndRequest(Prompt prompt, Prompt request, IList<I
prompt.Append(context);
}

if (request.Count >= 1)
if (IsSingleUserText(request))
{
prompt += RequestSection(request[0].GetText());
return prompt;
Expand All @@ -53,6 +55,10 @@ public static Prompt AddContextAndRequest(Prompt prompt, Prompt request, IList<I
return prompt;
}

/// <summary>Only an ordinary, single user text section can be wrapped without losing content or roles.</summary>
protected static bool IsSingleUserText(Prompt request) =>
request.Count == 1 && request[0].GetType() == typeof(PromptSection) && request[0].Source == PromptSection.Sources.User;

/// <summary>
/// Adds a section that tells the model that its task to is translate requests into JSON matching the
/// given schema
Expand All @@ -62,12 +68,13 @@ public static Prompt AddContextAndRequest(Prompt prompt, Prompt request, IList<I
/// <returns></returns>
public static PromptSection IntroSection(string typeName, string schema)
{
PromptSection introSection = new PromptSection();
introSection += $"You are a service that translates user requests into JSON objects of type \"{typeName}\" according to the following TypeScript definitions:\n";
introSection += $"###\n{schema}###\n";
return introSection;
return PromptSection.FromUser(SchemaInstructions(typeName, schema));
}

internal static string SchemaInstructions(string typeName, string schema) =>
$"You are a service that translates user requests into JSON objects of type \"{typeName}\" according to the following TypeScript definitions:\n" +
$"###\n{schema}###\n";

public static PromptSection RequestSection(string request)
{
PromptSection requestSection = new PromptSection();
Expand Down
6 changes: 6 additions & 0 deletions src/typechat/Prompt.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ namespace Microsoft.TypeChat;
/// </summary>
public class Prompt : List<IPromptSection>
{
/// <summary>
/// Permit a text-only model to join this prompt into a single string, losing message boundaries
/// and roles. The legacy translator prompts opt in; schema-first prompts do not.
/// </summary>
public bool AllowTextFlattening { get; set; }

/// <summary>
/// Create an empty prompt
/// </summary>
Expand Down
Loading
Loading