Compare commits

...
Author SHA1 Message Date
Dmytro StrukandGitHub 65b6b28ffe Update package versions (#3838) 2026-02-11 00:20:29 +00:00
Giles OdigweandGitHub 7a88af0aef Python: [BREAKING] Replace Hosted*Tool classes with tool methods (#3634)
* Replace Hosted*Tool classes with client static factory methods

* fixed failing test

* mypy fix

* mypy fix 2

* declarative mypy fix

* addressed comments

* ToolProtocol removal

* fixed test

* agents mypy fix

* fix failing tests

* mypy fix

* addressed comments

* fixed tests

* addressed comments + added factory method overrides for azureai v2 client

* mypy fix

* added kwargs to azureai tool methods

* fixed in test

* _sessions fix

* test fix
2026-02-11 00:04:27 +00:00
ChrisandGitHub d249473a6d Re-enabled (#3828) 2026-02-10 23:13:21 +00:00
CopilotGitHubcrickmancopilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>Chris RickmanCopilot
9f4c5f3faa .NET: Add unit tests for EditTableV2Executor (#3773)
* Initial plan

* Add comprehensive unit tests for EditTableV2Executor

- Test AddItemOperation with record and scalar values
- Test ClearItemsOperation
- Test RemoveItemOperation
- Test TakeLastItemOperation (with items and empty table)
- Test TakeFirstItemOperation (with items and empty table)
- Test error cases (null ItemsVariable, non-table variable)
- Include ExecuteTestAsync and CreateModel helper methods
- All 10 tests passing

Co-authored-by: crickman <66376200+crickman@users.noreply.github.com>

* Add comprehensive unit tests for EditTableV2Executor - complete with 100% coverage

- Added 13 comprehensive tests covering all code paths
- Test AddItemOperation with record and scalar values
- Test ClearItemsOperation
- Test RemoveItemOperation (including non-table value case)
- Test TakeLastItemOperation (with items and empty table)
- Test TakeFirstItemOperation (with items and empty table)
- Test error cases (null ItemsVariable, non-table variable, null operation values)
- Include ExecuteTestAsync and CreateModel helper methods
- 100% line and branch coverage achieved

Co-authored-by: crickman <66376200+crickman@users.noreply.github.com>

* Update tests / refine product code

* Checkpoint

* Updated

* Update dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/ObjectModel/SetTextVariableExecutorTest.cs

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Address code review feedback

- Fix typo: rename metadataExpresssion to metadataExpression
- Fix test name in AddMessageWithMetadataAsync (was using wrong test name)
- Fix test name in ClearGlobalScopeAsync (was using wrong test name)
- Remove pre-population in SetTextVariableExecutorTest that made tests ineffective
- Use explicit .Where() filter in SetMultipleVariablesExecutorTest foreach loop

Co-authored-by: crickman <66376200+crickman@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: crickman <66376200+crickman@users.noreply.github.com>
Co-authored-by: Chris Rickman <crickman@microsoft.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-02-10 23:11:49 +00:00
0521f5bed8 Python: [BREAKING] Simplify API: ChatAgent -> Agent, ChatMessage -> Message (#3747)
* [BREAKING] Rename ChatAgent -> Agent, ChatMessage -> Message, ChatClientProtocol -> SupportsChatGetResponse

Simplify the public API by removing redundant 'Chat' prefix from core types:
- ChatAgent -> Agent
- RawChatAgent -> RawAgent
- ChatMessage -> Message
- ChatClientProtocol -> SupportsChatGetResponse

Also renamed internal WorkflowMessage (was Message in _runner_context) to avoid collision.

No backward compatibility aliases - this is a clean breaking change.

* [BREAKING] Rename Agent chat_client parameter to client

* Fix rebase issues: WorkflowMessage references and broken markdown links

* Fix formatting and lint issues from code quality checks

* Fix import ordering in workflow sample files

* fixed rebase

* Fix test failures: use WorkflowMessage and A2AMessage after ChatMessage→Message rename

- Replace Message(data=..., source_id=...) with WorkflowMessage(...) in workflow tests
- Fix isinstance check in A2A agent to use A2AMessage instead of Message
- Fix import in test_workflow_observability.py (Message→WorkflowMessage)

* Fix lint, fmt, and sample errors after ChatMessage→Message rename

- Auto-fix 70+ ruff lint issues across samples (ChatMessage→Message refs)
- Fix HostedVectorStoreContent→Content.from_hosted_vector_store in file search sample
- Fix _normalize_messages→normalize_messages in custom agent sample
- Fix context.terminate→raise MiddlewareTermination in middleware samples
- Fix with_update_hook→with_transform_hook in override middleware sample
- Add TOptions_co import back to custom_chat_client sample
- Add noqa for FastAPI File() default in chatkit sample
- Fix B023 loop variable capture in weather agent sample

* fix: update Agent constructor calls from chat_client to client in declaration-only tool tests

* fix: add register_cleanup to devui lazy-loading proxy and type stub

* fixed tests and updated new pieces

* fix agui typevar

* fix merge errors

* fix merge conflicts

* fiux merge

* Remove unused links

---------

Co-authored-by: Evan Mattson <evan.mattson@microsoft.com>
2026-02-10 23:04:32 +00:00
Evan MattsonandGitHub a4c9e43afb [BREAKING] Python: Remove workflow register factory methods. Update tests and samples (#3781)
* Remove workflow register factory methods. Update tests and samples

* Address Copilot feedback
2026-02-10 22:16:17 +00:00
ChrisandGitHub f407f726a7 .NET Workflows - Remove empty message injection in declarative workflow agent provider. (#3819)
* Fixed

* Update test-case expectations
2026-02-10 21:25:40 +00:00
Eduard van ValkenburgandGitHub ac0e6b0ee1 Python: PR1 — New session and context provider types (side-by-side) (#3763)
* PR1: Add core context provider types and tests

New types in _sessions.py (no changes to existing code):
- SessionContext: per-invocation state with extend_messages/get_messages/
  extend_instructions/extend_tools and read-only response property
- _ContextProviderBase: base class with before_run/after_run hooks
- _HistoryProviderBase: storage base with load/store flags, abstract
  get_messages/save_messages, default before_run/after_run
- AgentSession: lightweight session with state dict, to_dict/from_dict
- InMemoryHistoryProvider: built-in provider storing in session.state

35 unit tests covering all classes and configuration flags.

* feat: keyword-only params, stateless InMemoryHistoryProvider, deep serialization

- Make before_run/after_run parameters keyword-only
- InMemoryHistoryProvider stores ChatMessage objects directly (no per-cycle serialization)
- Deep serialization via to_dict/from_dict only at session boundary
- State type registry for automatic deserialization of registered types
- Updated tests for new serialization approach

* feat: add new-pattern provider implementations for external packages

- _RedisContextProvider(BaseContextProvider) - Redis search/vector context
- _RedisHistoryProvider(BaseHistoryProvider) - Redis-backed message storage
- _Mem0ContextProvider(BaseContextProvider) - Mem0 semantic memory
- _AzureAISearchContextProvider(BaseContextProvider) - Azure AI Search (semantic + agentic)

All use temporary _ prefix names for side-by-side coexistence with existing providers.
Will be renamed in PR2 when old ContextProvider/ChatMessageStore are removed.

* test: add tests for new-pattern provider implementations

- 32 tests for _RedisContextProvider and _RedisHistoryProvider
- 29 tests for _Mem0ContextProvider
- 17 tests for _AzureAISearchContextProvider

* fix: address PR review comments and CI failures

- Move module docstring before imports in _sessions.py (review comment)
- Import TYPE_CHECKING unconditionally in Redis _context_provider.py (NameError on Python <3.12)
- Fix Mem0 test_init_auto_creates_client_when_none to patch at class level

* feat: add source attribution to extend_messages

Set attribution marker in additional_properties for each message
added via extend_messages(), matching the tool attribution pattern.
Uses setdefault to preserve any existing attribution.

* refactor: make attribution value a dict with source_id key

* add attribution and use sets for filters

* Add source_type to message attribution and copy messages in extend_messages

- SessionContext.extend_messages now accepts source as str or object with
  source_id attribute; when an object is passed, its class name is recorded
  as source_type in the attribution dict
- Messages are shallow-copied before attribution is added so callers'
  original objects are never mutated
- Filter framework-internal keys (attribution) from A2A wire metadata
  to prevent leaking internal state over the wire

* fix: correct mypy type: ignore comment from union-attr to attr-defined

* set attribution to _attribution

* adjusted naming of bools
2026-02-10 21:19:15 +00:00
ChrisandGitHub ccff3d3452 Updated (#3772) 2026-02-10 21:15:59 +00:00
Eduard van ValkenburgandGitHub 35097d8c75 Python: Add long-running agents and background responses support (#3808)
* Python: Add long-running agents and background responses support

- Add ContinuationToken TypedDict to core types
- Add continuation_token field to ChatResponse, ChatResponseUpdate,
  AgentResponse, and AgentResponseUpdate
- Add background and continuation_token options to OpenAIResponsesOptions
- Implement polling via responses.retrieve() and streaming resumption
  in RawOpenAIResponsesClient
- Propagate continuation tokens through agent run() and
  map_chat_to_agent_update
- Fix streaming telemetry 'Failed to detach context' error in both
  ChatTelemetryLayer and AgentTelemetryLayer by avoiding
  trace.use_span() context attachment for async-managed spans
- Add 14 unit tests for continuation token types and background flows
- Add background_responses sample showing polling and stream resumption

Fixes #2478

* Python: Add A2A long-running task support via ContinuationToken

- Make ContinuationToken provider-agnostic (total=False, optional task_id/context_id fields)
- Add background param to A2AAgent.run() controlling token emission
- Add poll_task() for single-request task state retrieval
- Add resubscribe support via continuation_token param on run()
- Extract _updates_from_task() and _map_a2a_stream() for cleaner code
- Streamline run()/streaming by removing intermediate _stream_updates wrapper
- Update A2A sample to show background=False (default) with link to background_responses sample
- Remove stale BareAgent from __all__
- Add 12 new A2A continuation token tests

* fix logic for overriding continuation token when done

* refactored ContinuationToken setup
2026-02-10 20:37:43 +00:00
Giles OdigweandGitHub 32ba81e990 Python: Add documentation for declaration-only tools and middleware ordering (#3774)
* added explanation doctrings

* copilot comments
2026-02-10 20:14:28 +00:00
Giles OdigweandGitHub 84cb09cb68 Python: Add streaming support for code interpreter deltas (#3775)
* add streaming support for code interpreter deltas

* addressed copilot comments

* mypy fix
2026-02-10 19:43:33 +00:00
Giles OdigweandGitHub a149aaa926 Python: [BREAKING] Standardize TypeVar naming convention (TName → NameT) (#3770)
* standardized typevar to use suffix T

* addressed copilot comments
2026-02-10 19:34:10 +00:00
7dccf3a07b .NET: [BREAKING] Update message source code to match python. (#3805)
* Update message source code to match python.

* Apply suggestion from @Copilot

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Address PR comment

* Move setting of source information to extension method

* Add underscore for attribution key to indicate internal usage

* Stick to version 102 of the SDK since 103 is causing issues.

* Revert global.json change

* Fix unit test

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-02-10 19:21:18 +00:00
Rishabh ChawlaandGitHub 7e7d72275d Python: [Purview] Update CorrelationId (#3745) 2026-02-10 19:19:14 +00:00
Evan MattsonandGitHub f106a1a2b1 Python: Include sub-workflow structure in graph signature for checkpoint validation (#3783)
* Include sub-workflow structure in graph signature for checkpoint validation

* Remove redundant computation
2026-02-10 17:24:27 +00:00
Roger BarretoandGitHub aa44e63074 .NET: Add Foundry Agents Tool Sample - Local MCP (#3703)
* .NET: Add Local MCP sample #3674

* Apply format fixes

* .NET: Use local MCP client instead of hosted MCP in Step27 sample

* Address PR review feedback: cleanup, try/finally, update parent README
2026-02-10 16:50:55 +00:00
617 changed files with 16191 additions and 24721 deletions
@@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFrameworks>net10.0</TargetFrameworks>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<NoWarn>$(NoWarn);CA1812</NoWarn>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Azure.Identity" />
<PackageReference Include="Azure.AI.Projects" />
<PackageReference Include="ModelContextProtocol" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.AzureAI\Microsoft.Agents.AI.AzureAI.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,83 @@
// Copyright (c) Microsoft. All rights reserved.
// This sample demonstrates how to use a local MCP (Model Context Protocol) client with Azure Foundry Agents.
// The MCP tools are resolved locally by connecting directly to the MCP server via HTTP,
// and then passed to the Foundry agent as client-side tools.
// This sample uses the Microsoft Learn MCP endpoint to search documentation.
using Azure.AI.Projects;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
using ModelContextProtocol.Client;
string endpoint = Environment.GetEnvironmentVariable("AZURE_FOUNDRY_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("AZURE_FOUNDRY_PROJECT_ENDPOINT is not set.");
string deploymentName = Environment.GetEnvironmentVariable("AZURE_FOUNDRY_PROJECT_DEPLOYMENT_NAME") ?? "gpt-4o-mini";
const string AgentInstructions = "You are a helpful assistant that can help with Microsoft documentation questions. Use the Microsoft Learn MCP tool to search for documentation.";
const string AgentName = "DocsAgent";
// Connect to the MCP server locally via HTTP (Streamable HTTP transport).
// The MCP server is hosted at Microsoft Learn and provides documentation search capabilities.
Console.WriteLine("Connecting to MCP server at https://learn.microsoft.com/api/mcp ...");
await using McpClient mcpClient = await McpClient.CreateAsync(new HttpClientTransport(new()
{
Endpoint = new Uri("https://learn.microsoft.com/api/mcp"),
Name = "Microsoft Learn MCP",
}));
// Retrieve the list of tools available on the MCP server (resolved locally).
IList<McpClientTool> mcpTools = await mcpClient.ListToolsAsync();
Console.WriteLine($"MCP tools available: {string.Join(", ", mcpTools.Select(t => t.Name))}");
// Wrap each MCP tool with a DelegatingAIFunction to log local invocations.
List<AITool> wrappedTools = mcpTools.Select(tool => (AITool)new LoggingMcpTool(tool)).ToList();
// Get a client to create/retrieve/delete server side agents with Azure Foundry Agents.
AIProjectClient aiProjectClient = new(new Uri(endpoint), new AzureCliCredential());
// Create the agent with the locally-resolved MCP tools.
AIAgent agent = await aiProjectClient.CreateAIAgentAsync(
model: deploymentName,
name: AgentName,
instructions: AgentInstructions,
tools: wrappedTools);
Console.WriteLine($"Agent '{agent.Name}' created successfully.");
try
{
// First query
const string Prompt1 = "How does one create an Azure storage account using az cli?";
Console.WriteLine($"\nUser: {Prompt1}\n");
AgentResponse response1 = await agent.RunAsync(Prompt1);
Console.WriteLine($"Agent: {response1}");
Console.WriteLine("\n=======================================\n");
// Second query
const string Prompt2 = "What is Microsoft Agent Framework?";
Console.WriteLine($"User: {Prompt2}\n");
AgentResponse response2 = await agent.RunAsync(Prompt2);
Console.WriteLine($"Agent: {response2}");
}
finally
{
// Cleanup by removing the agent when done
await aiProjectClient.Agents.DeleteAgentAsync(agent.Name);
Console.WriteLine($"\nAgent '{agent.Name}' deleted.");
}
/// <summary>
/// Wraps an MCP tool to log when it is invoked locally,
/// confirming that the MCP call is happening client-side.
/// </summary>
internal sealed class LoggingMcpTool(AIFunction innerFunction) : DelegatingAIFunction(innerFunction)
{
protected override ValueTask<object?> InvokeCoreAsync(AIFunctionArguments arguments, CancellationToken cancellationToken)
{
Console.WriteLine($" >> [LOCAL MCP] Invoking tool '{this.Name}' locally...");
return base.InvokeCoreAsync(arguments, cancellationToken);
}
}
@@ -0,0 +1,48 @@
# Using Local MCP Client with Azure Foundry Agents
This sample demonstrates how to use a local MCP (Model Context Protocol) client with Azure Foundry Agents. Unlike the hosted MCP approach where Azure Foundry invokes the MCP server on the service side, this sample connects to the MCP server directly from the client via HTTP (Streamable HTTP transport) and passes the resolved tools to the agent.
## What this sample demonstrates
- Connecting to an MCP server locally using `HttpClientTransport`
- Discovering available tools from the MCP server client-side
- Passing locally-resolved MCP tools to a Foundry agent
- Using the Microsoft Learn MCP endpoint for documentation search
- Managing agent lifecycle (creation and deletion)
## Prerequisites
Before you begin, ensure you have the following prerequisites:
- .NET 10 SDK or later
- Azure Foundry service endpoint and deployment configured
- Azure CLI installed and authenticated (for Azure credential authentication)
**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Azure Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively).
Set the following environment variables:
```powershell
$env:AZURE_FOUNDRY_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Azure Foundry resource endpoint
$env:AZURE_FOUNDRY_PROJECT_DEPLOYMENT_NAME="gpt-4o-mini" # Optional, defaults to gpt-4o-mini
```
## Run the sample
Navigate to the FoundryAgents sample directory and run:
```powershell
cd dotnet/samples/GettingStarted/FoundryAgents
dotnet run --project .\FoundryAgents_Step27_LocalMCP
```
## Expected behavior
The sample will:
1. Connect to the Microsoft Learn MCP server via HTTP and list available tools
2. Create an agent with the locally-resolved MCP tools
3. Ask two questions about Microsoft documentation
4. The agent will use the MCP tools (invoked locally) to search Microsoft Learn documentation
5. Display the agent's responses with information from the documentation
6. Clean up resources by deleting the agent
@@ -58,6 +58,7 @@ Before you begin, ensure you have the following prerequisites:
|[Using plugins](./FoundryAgents_Step13_Plugins/)|This sample demonstrates how to use plugins with a Foundry agent|
|[Code interpreter](./FoundryAgents_Step14_CodeInterpreter/)|This sample demonstrates how to use the code interpreter tool with a Foundry agent|
|[Computer use](./FoundryAgents_Step15_ComputerUse/)|This sample demonstrates how to use computer use capabilities with a Foundry agent|
|[Local MCP](./FoundryAgents_Step27_LocalMCP/)|This sample demonstrates how to use a local MCP client with a Foundry agent|
## Running the samples from the console
@@ -32,23 +32,23 @@ namespace Microsoft.Agents.AI;
/// </remarks>
public abstract class AIContextProvider
{
private readonly string _sourceName;
private readonly string _sourceId;
/// <summary>
/// Initializes a new instance of the <see cref="AIContextProvider"/> class.
/// </summary>
protected AIContextProvider()
{
this._sourceName = this.GetType().FullName!;
this._sourceId = this.GetType().FullName!;
}
/// <summary>
/// Initializes a new instance of the <see cref="AIContextProvider"/> class with the specified source name.
/// Initializes a new instance of the <see cref="AIContextProvider"/> class with the specified source id.
/// </summary>
/// <param name="sourceName">The source name to stamp on <see cref="ChatMessage.AdditionalProperties"/> for each messages produced by the <see cref="AIContextProvider"/>.</param>
protected AIContextProvider(string sourceName)
/// <param name="sourceId">The source id to stamp on <see cref="ChatMessage.AdditionalProperties"/> for each messages produced by the <see cref="AIContextProvider"/>.</param>
protected AIContextProvider(string sourceId)
{
this._sourceName = sourceName;
this._sourceId = sourceId;
}
/// <summary>
@@ -76,27 +76,9 @@ public abstract class AIContextProvider
return aiContext;
}
aiContext.Messages = aiContext.Messages.Select(message =>
{
if (message.AdditionalProperties != null
// Check if the message was already tagged with this provider's source type
&& message.AdditionalProperties.TryGetValue(AgentRequestMessageSourceType.AdditionalPropertiesKey, out var messageSourceType)
&& messageSourceType is AgentRequestMessageSourceType typedMessageSourceType
&& typedMessageSourceType == AgentRequestMessageSourceType.AIContextProvider
// Check if the message was already tagged with this provider's source
&& message.AdditionalProperties.TryGetValue(AgentRequestMessageSource.AdditionalPropertiesKey, out var messageSource)
&& messageSource is string typedMessageSource
&& typedMessageSource == this._sourceName)
{
return message;
}
message = message.Clone();
message.AdditionalProperties ??= new();
message.AdditionalProperties[AgentRequestMessageSourceType.AdditionalPropertiesKey] = AgentRequestMessageSourceType.AIContextProvider;
message.AdditionalProperties[AgentRequestMessageSource.AdditionalPropertiesKey] = this._sourceName;
return message;
}).ToList();
aiContext.Messages = aiContext.Messages
.Select(message => message.AsAgentRequestMessageSourcedMessage(AgentRequestMessageSourceType.AIContextProvider, this._sourceId))
.ToList();
return aiContext;
}
@@ -1,16 +0,0 @@
// Copyright (c) Microsoft. All rights reserved.
using Microsoft.Extensions.AI;
namespace Microsoft.Agents.AI;
/// <summary>
/// Provides a constant for the key used to store the source of the agent request message.
/// </summary>
public static class AgentRequestMessageSource
{
/// <summary>
/// Provides the key used in <see cref="ChatMessage.AdditionalProperties"/> to store the source of the agent request message.
/// </summary>
public static readonly string AdditionalPropertiesKey = "Agent.RequestMessageSource";
}
@@ -0,0 +1,102 @@
// Copyright (c) Microsoft. All rights reserved.
using System;
using Microsoft.Extensions.AI;
namespace Microsoft.Agents.AI;
/// <summary>
/// Represents attribution information for the source of an agent request message for a specific run, including the component type and
/// identifier.
/// </summary>
/// <remarks>
/// Use this struct to identify which component provided a message during an agent run.
/// This is useful to allow filtering of messages based on their source, such as distinguishing between user input, middleware-generated messages, and chat history.
/// </remarks>
public readonly struct AgentRequestMessageSourceAttribution : IEquatable<AgentRequestMessageSourceAttribution>
{
/// <summary>
/// Provides the key used in <see cref="ChatMessage.AdditionalProperties"/> to store the <see cref="AgentRequestMessageSourceAttribution"/>
/// associated with the agent request message.
/// </summary>
public static readonly string AdditionalPropertiesKey = "_attribution";
/// <summary>
/// Initializes a new instance of the <see cref="AgentRequestMessageSourceAttribution"/> struct with the specified source type and identifier.
/// </summary>
/// <param name="sourceType">The <see cref="AgentRequestMessageSourceType"/> of the component that provided the message.</param>
/// <param name="sourceId">The unique identifier of the component that provided the message.</param>
public AgentRequestMessageSourceAttribution(AgentRequestMessageSourceType sourceType, string? sourceId)
{
this.SourceType = sourceType;
this.SourceId = sourceId;
}
/// <summary>
/// Gets the type of component that provided the message for the current agent run.
/// </summary>
public AgentRequestMessageSourceType SourceType { get; }
/// <summary>
/// Gets the unique identifier of the component that provided the message for the current agent run.
/// </summary>
public string? SourceId { get; }
/// <summary>
/// Determines whether the specified <see cref="AgentRequestMessageSourceAttribution"/> is equal to the current instance.
/// </summary>
/// <param name="other">The <see cref="AgentRequestMessageSourceAttribution"/> to compare with the current instance.</param>
/// <returns><see langword="true"/> if the specified instance is equal to the current instance; otherwise, <see langword="false"/>.</returns>
public bool Equals(AgentRequestMessageSourceAttribution other)
{
return this.SourceType == other.SourceType &&
string.Equals(this.SourceId, other.SourceId, StringComparison.Ordinal);
}
/// <summary>
/// Determines whether the specified object is equal to the current instance.
/// </summary>
/// <param name="obj">The object to compare with the current instance.</param>
/// <returns><see langword="true"/> if the specified object is equal to the current instance; otherwise, <see langword="false"/>.</returns>
public override bool Equals(object? obj)
{
return obj is AgentRequestMessageSourceAttribution other && this.Equals(other);
}
/// <summary>
/// Returns a hash code for the current instance.
/// </summary>
/// <returns>A hash code for the current instance.</returns>
public override int GetHashCode()
{
unchecked
{
int hash = 17;
hash = (hash * 31) + this.SourceType.GetHashCode();
hash = (hash * 31) + (this.SourceId?.GetHashCode() ?? 0);
return hash;
}
}
/// <summary>
/// Determines whether two <see cref="AgentRequestMessageSourceAttribution"/> instances are equal.
/// </summary>
/// <param name="left">The first instance to compare.</param>
/// <param name="right">The second instance to compare.</param>
/// <returns><see langword="true"/> if the instances are equal; otherwise, <see langword="false"/>.</returns>
public static bool operator ==(AgentRequestMessageSourceAttribution left, AgentRequestMessageSourceAttribution right)
{
return left.Equals(right);
}
/// <summary>
/// Determines whether two <see cref="AgentRequestMessageSourceAttribution"/> instances are not equal.
/// </summary>
/// <param name="left">The first instance to compare.</param>
/// <param name="right">The second instance to compare.</param>
/// <returns><see langword="true"/> if the instances are not equal; otherwise, <see langword="false"/>.</returns>
public static bool operator !=(AgentRequestMessageSourceAttribution left, AgentRequestMessageSourceAttribution right)
{
return !left.Equals(right);
}
}
@@ -1,7 +1,6 @@
// Copyright (c) Microsoft. All rights reserved.
using System;
using Microsoft.Extensions.AI;
using Microsoft.Shared.Diagnostics;
namespace Microsoft.Agents.AI;
@@ -14,15 +13,10 @@ namespace Microsoft.Agents.AI;
/// This type helps to identify whether a message came from outside the agent pipeline,
/// whether it was produced by middleware, or came from chat history.
/// </remarks>
public sealed class AgentRequestMessageSourceType : IEquatable<AgentRequestMessageSourceType>
public readonly struct AgentRequestMessageSourceType : IEquatable<AgentRequestMessageSourceType>
{
/// <summary>
/// Provides the key used in <see cref="ChatMessage.AdditionalProperties"/> to store the source type of the agent request message.
/// </summary>
public static readonly string AdditionalPropertiesKey = "Agent.RequestMessageSourceType";
/// <summary>
/// Initializes a new instance of the <see cref="AgentRequestMessageSourceType"/> class.
/// Initializes a new instance of the <see cref="AgentRequestMessageSourceType"/> struct.
/// </summary>
/// <param name="value">The string value representing the source of the agent request message.</param>
public AgentRequestMessageSourceType(string value) => this.Value = Throw.IfNullOrWhitespace(value);
@@ -30,7 +24,7 @@ public sealed class AgentRequestMessageSourceType : IEquatable<AgentRequestMessa
/// <summary>
/// Get the string value representing the source of the agent request message.
/// </summary>
public string Value { get; }
public string Value { get { return field ?? External.Value; } }
/// <summary>
/// The message came from outside the agent pipeline (e.g., user input).
@@ -52,18 +46,8 @@ public sealed class AgentRequestMessageSourceType : IEquatable<AgentRequestMessa
/// </summary>
/// <param name="other">The <see cref="AgentRequestMessageSourceType"/> to compare to this instance.</param>
/// <returns><see langword="true"/> if the value of the <paramref name="other"/> parameter is the same as the value of this instance; otherwise, <see langword="false"/>.</returns>
public bool Equals(AgentRequestMessageSourceType? other)
public bool Equals(AgentRequestMessageSourceType other)
{
if (other is null)
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return string.Equals(this.Value, other.Value, StringComparison.Ordinal);
}
@@ -72,7 +56,7 @@ public sealed class AgentRequestMessageSourceType : IEquatable<AgentRequestMessa
/// </summary>
/// <param name="obj">The object to compare to this instance.</param>
/// <returns><see langword="true"/> if <paramref name="obj"/> is a <see cref="AgentRequestMessageSourceType"/> and its value is the same as this instance; otherwise, <see langword="false"/>.</returns>
public override bool Equals(object? obj) => this.Equals(obj as AgentRequestMessageSourceType);
public override bool Equals(object? obj) => obj is AgentRequestMessageSourceType other && this.Equals(other);
/// <summary>
/// Returns the hash code for this instance.
@@ -86,13 +70,8 @@ public sealed class AgentRequestMessageSourceType : IEquatable<AgentRequestMessa
/// <param name="left">The first <see cref="AgentRequestMessageSourceType"/> to compare.</param>
/// <param name="right">The second <see cref="AgentRequestMessageSourceType"/> to compare.</param>
/// <returns><see langword="true"/> if the value of <paramref name="left"/> is the same as the value of <paramref name="right"/>; otherwise, <see langword="false"/>.</returns>
public static bool operator ==(AgentRequestMessageSourceType? left, AgentRequestMessageSourceType? right)
public static bool operator ==(AgentRequestMessageSourceType left, AgentRequestMessageSourceType right)
{
if (left is null)
{
return right is null;
}
return left.Equals(right);
}
@@ -102,5 +81,5 @@ public sealed class AgentRequestMessageSourceType : IEquatable<AgentRequestMessa
/// <param name="left">The first <see cref="AgentRequestMessageSourceType"/> to compare.</param>
/// <param name="right">The second <see cref="AgentRequestMessageSourceType"/> to compare.</param>
/// <returns><see langword="true"/> if the value of <paramref name="left"/> is different from the value of <paramref name="right"/>; otherwise, <see langword="false"/>.</returns>
public static bool operator !=(AgentRequestMessageSourceType? left, AgentRequestMessageSourceType? right) => !(left == right);
public static bool operator !=(AgentRequestMessageSourceType left, AgentRequestMessageSourceType right) => !(left == right);
}
@@ -37,23 +37,23 @@ namespace Microsoft.Agents.AI;
/// </remarks>
public abstract class ChatHistoryProvider
{
private readonly string _sourceName;
private readonly string _sourceId;
/// <summary>
/// Initializes a new instance of the <see cref="ChatHistoryProvider"/> class.
/// </summary>
protected ChatHistoryProvider()
{
this._sourceName = this.GetType().FullName!;
this._sourceId = this.GetType().FullName!;
}
/// <summary>
/// Initializes a new instance of the <see cref="ChatHistoryProvider"/> class with the specified source name.
/// Initializes a new instance of the <see cref="ChatHistoryProvider"/> class with the specified source id.
/// </summary>
/// <param name="sourceName">The source name to stamp on <see cref="ChatMessage.AdditionalProperties"/> for each messages produced by the <see cref="ChatHistoryProvider"/>.</param>
protected ChatHistoryProvider(string sourceName)
/// <param name="sourceId">The source id to stamp on <see cref="ChatMessage.AdditionalProperties"/> for each messages produced by the <see cref="ChatHistoryProvider"/>.</param>
protected ChatHistoryProvider(string sourceId)
{
this._sourceName = sourceName;
this._sourceId = sourceId;
}
/// <summary>
@@ -89,27 +89,7 @@ public abstract class ChatHistoryProvider
{
var messages = await this.InvokingCoreAsync(context, cancellationToken).ConfigureAwait(false);
return messages.Select(message =>
{
if (message.AdditionalProperties != null
// Check if the message was already tagged with this provider's source type
&& message.AdditionalProperties.TryGetValue(AgentRequestMessageSourceType.AdditionalPropertiesKey, out var messageSourceType)
&& messageSourceType is AgentRequestMessageSourceType typedMessageSourceType
&& typedMessageSourceType == AgentRequestMessageSourceType.ChatHistory
// Check if the message was already tagged with this provider's source
&& message.AdditionalProperties.TryGetValue(AgentRequestMessageSource.AdditionalPropertiesKey, out var messageSource)
&& messageSource is string typedMessageSource
&& typedMessageSource == this._sourceName)
{
return message;
}
message = message.Clone();
message.AdditionalProperties ??= new();
message.AdditionalProperties[AgentRequestMessageSourceType.AdditionalPropertiesKey] = AgentRequestMessageSourceType.ChatHistory;
message.AdditionalProperties[AgentRequestMessageSource.AdditionalPropertiesKey] = this._sourceName;
return message;
});
return messages.Select(message => message.AsAgentRequestMessageSourcedMessage(AgentRequestMessageSourceType.ChatHistory, this._sourceId));
}
/// <summary>
@@ -45,7 +45,7 @@ public static class ChatHistoryProviderExtensions
innerProvider: provider,
invokedMessagesFilter: (ctx) =>
{
ctx.RequestMessages = ctx.RequestMessages.Where(x => x.GetAgentRequestMessageSource() != AgentRequestMessageSourceType.AIContextProvider);
ctx.RequestMessages = ctx.RequestMessages.Where(x => x.GetAgentRequestMessageSourceType() != AgentRequestMessageSourceType.AIContextProvider);
return ctx;
});
}
@@ -10,18 +10,66 @@ namespace Microsoft.Agents.AI;
public static class ChatMessageExtensions
{
/// <summary>
/// Gets the source of the provided <see cref="ChatMessage"/> in the context of messages passed into an agent run.
/// Gets the source type of the provided <see cref="ChatMessage"/> in the context of messages passed into an agent run.
/// </summary>
/// <param name="message">The <see cref="ChatMessage"/> for which we need the source.</param>
/// <returns>An <see cref="AgentRequestMessageSourceType"/> value indicating the source of the <see cref="ChatMessage"/>. Defaults to <see
/// <param name="message">The <see cref="ChatMessage"/> for which we need the source type.</param>
/// <returns>An <see cref="AgentRequestMessageSourceType"/> value indicating the source type of the <see cref="ChatMessage"/>. Defaults to <see
/// cref="AgentRequestMessageSourceType.External"/> if no explicit source is defined.</returns>
public static AgentRequestMessageSourceType GetAgentRequestMessageSource(this ChatMessage message)
public static AgentRequestMessageSourceType GetAgentRequestMessageSourceType(this ChatMessage message)
{
if (message.AdditionalProperties?.TryGetValue(AgentRequestMessageSourceType.AdditionalPropertiesKey, out var source) is true && source is AgentRequestMessageSourceType typedSource)
if (message.AdditionalProperties?.TryGetValue(AgentRequestMessageSourceAttribution.AdditionalPropertiesKey, out var attribution) is true
&& attribution is AgentRequestMessageSourceAttribution typedAttribution)
{
return typedSource;
return typedAttribution.SourceType;
}
return AgentRequestMessageSourceType.External;
}
/// <summary>
/// Gets the source id of the provided <see cref="ChatMessage"/> in the context of messages passed into an agent run.
/// </summary>
/// <param name="message">The <see cref="ChatMessage"/> for which we need the source id.</param>
/// <returns>An <see cref="string"/> value indicating the source id of the <see cref="ChatMessage"/>. Defaults to <see langword="null"/>
/// if no explicit source id is defined.</returns>
public static string? GetAgentRequestMessageSourceId(this ChatMessage message)
{
if (message.AdditionalProperties?.TryGetValue(AgentRequestMessageSourceAttribution.AdditionalPropertiesKey, out var attribution) is true
&& attribution is AgentRequestMessageSourceAttribution typedAttribution)
{
return typedAttribution.SourceId;
}
return null;
}
/// <summary>
/// Ensure that the provided message is tagged with the provided source type and source id in the context of a specific agent run.
/// </summary>
/// <param name="message">The message to tag.</param>
/// <param name="sourceType">The source type to tag the message with.</param>
/// <param name="sourceId">The source id to tag the message with.</param>
/// <returns>The tagged message.</returns>
/// <remarks>
/// If the message is already tagged with the provided source type and source id, it is returned as is.
/// Otherwise, a cloned message is returned with the appropriate tagging in the AdditionalProperties.
/// </remarks>
public static ChatMessage AsAgentRequestMessageSourcedMessage(this ChatMessage message, AgentRequestMessageSourceType sourceType, string? sourceId = null)
{
if (message.AdditionalProperties != null
// Check if the message was already tagged with the required source type and source id
&& message.AdditionalProperties.TryGetValue(AgentRequestMessageSourceAttribution.AdditionalPropertiesKey, out var messageSourceAttribution)
&& messageSourceAttribution is AgentRequestMessageSourceAttribution typedMessageSourceAttribution
&& typedMessageSourceAttribution.SourceType == sourceType
&& typedMessageSourceAttribution.SourceId == sourceId)
{
return message;
}
message = message.Clone();
message.AdditionalProperties ??= new();
message.AdditionalProperties[AgentRequestMessageSourceAttribution.AdditionalPropertiesKey] =
new AgentRequestMessageSourceAttribution(sourceType, sourceId);
return message;
}
}
@@ -138,7 +138,7 @@ public sealed class Mem0Provider : AIContextProvider
string queryText = string.Join(
Environment.NewLine,
context.RequestMessages
.Where(m => m.GetAgentRequestMessageSource() == AgentRequestMessageSourceType.External)
.Where(m => m.GetAgentRequestMessageSourceType() == AgentRequestMessageSourceType.External)
.Where(m => !string.IsNullOrWhiteSpace(m.Text))
.Select(m => m.Text));
@@ -217,7 +217,7 @@ public sealed class Mem0Provider : AIContextProvider
// Persist request and response messages after invocation.
await this.PersistMessagesAsync(
context.RequestMessages
.Where(m => m.GetAgentRequestMessageSource() == AgentRequestMessageSourceType.External)
.Where(m => m.GetAgentRequestMessageSourceType() == AgentRequestMessageSourceType.External)
.Concat(context.ResponseMessages ?? []),
cancellationToken).ConfigureAwait(false);
}
@@ -21,12 +21,14 @@ internal abstract class ProcessContentMetadataBase : GraphDataTypeBase
/// <param name="identifier">The unique identifier for the content.</param>
/// <param name="isTruncated">Indicates if the content is truncated.</param>
/// <param name="name">The name of the content.</param>
protected ProcessContentMetadataBase(ContentBase content, string identifier, bool isTruncated, string name) : base(ProcessConversationMetadataDataType)
/// <param name="correlationId">The correlation ID for the content.</param>
protected ProcessContentMetadataBase(ContentBase content, string identifier, bool isTruncated, string name, string correlationId) : base(ProcessConversationMetadataDataType)
{
this.Identifier = identifier;
this.IsTruncated = isTruncated;
this.Content = content;
this.Name = name;
this.CorrelationId = correlationId;
}
/// <summary>
@@ -55,7 +57,7 @@ internal abstract class ProcessContentMetadataBase : GraphDataTypeBase
/// Identifier to group multiple contents.
/// </summary>
[JsonPropertyName("correlationId")]
public string? CorrelationId { get; set; }
public string CorrelationId { get; set; }
/// <summary>
/// Gets or sets the sequenceNumber.
@@ -15,7 +15,7 @@ internal sealed class ProcessConversationMetadata : ProcessContentMetadataBase
/// <summary>
/// Initializes a new instance of the <see cref="ProcessConversationMetadata"/> class.
/// </summary>
public ProcessConversationMetadata(ContentBase contentBase, string identifier, bool isTruncated, string name) : base(contentBase, identifier, isTruncated, name)
public ProcessConversationMetadata(ContentBase contentBase, string identifier, bool isTruncated, string name, string correlationId) : base(contentBase, identifier, isTruncated, name, correlationId)
{
this.DataType = ProcessConversationMetadataDataType;
}
@@ -14,7 +14,7 @@ internal sealed class ProcessFileMetadata : ProcessContentMetadataBase
/// <summary>
/// Initializes a new instance of the <see cref="ProcessFileMetadata"/> class.
/// </summary>
public ProcessFileMetadata(ContentBase contentBase, string identifier, bool isTruncated, string name) : base(contentBase, identifier, isTruncated, name)
public ProcessFileMetadata(ContentBase contentBase, string identifier, bool isTruncated, string name, string correlationId) : base(contentBase, identifier, isTruncated, name, correlationId)
{
this.DataType = ProcessFileMetadataDataType;
}
@@ -19,7 +19,7 @@ public class PurviewSettings
/// <param name="appName">The publicly visible name of the application.</param>
public PurviewSettings(string appName)
{
this.AppName = appName;
this.AppName = string.IsNullOrWhiteSpace(appName) ? throw new ArgumentException("AppName cannot be null or whitespace.", nameof(appName)) : appName;
}
/// <summary>
@@ -53,7 +53,7 @@ internal sealed class PurviewWrapper : IDisposable
}
}
return Guid.NewGuid().ToString();
return string.Empty;
}
/// <summary>
@@ -136,12 +136,15 @@ internal sealed class PurviewWrapper : IDisposable
/// <returns>The agent's response. This could be the response from the agent or a message indicating that Purview has blocked the prompt or response.</returns>
public async Task<AgentResponse> ProcessAgentContentAsync(IEnumerable<ChatMessage> messages, AgentSession? session, AgentRunOptions? options, AIAgent innerAgent, CancellationToken cancellationToken)
{
string sessionId = GetSessionIdFromAgentSession(session, messages);
string? resolvedUserId = null;
string sessionId = string.Empty;
try
{
sessionId = GetSessionIdFromAgentSession(session, messages);
if (string.IsNullOrEmpty(sessionId))
{
sessionId = Guid.NewGuid().ToString();
}
(bool shouldBlockPrompt, resolvedUserId) = await this._scopedProcessor.ProcessMessagesAsync(messages, sessionId, Activity.UploadText, this._purviewSettings, null, cancellationToken).ConfigureAwait(false);
if (shouldBlockPrompt)
@@ -171,7 +174,19 @@ internal sealed class PurviewWrapper : IDisposable
try
{
(bool shouldBlockResponse, _) = await this._scopedProcessor.ProcessMessagesAsync(response.Messages, sessionId, Activity.UploadText, this._purviewSettings, resolvedUserId, cancellationToken).ConfigureAwait(false);
string sessionIdResponse = GetSessionIdFromAgentSession(session, messages);
if (string.IsNullOrEmpty(sessionIdResponse))
{
if (string.IsNullOrEmpty(sessionId))
{
sessionIdResponse = Guid.NewGuid().ToString();
}
else
{
sessionIdResponse = sessionId;
}
}
(bool shouldBlockResponse, _) = await this._scopedProcessor.ProcessMessagesAsync(response.Messages, sessionIdResponse, Activity.UploadText, this._purviewSettings, resolvedUserId, cancellationToken).ConfigureAwait(false);
if (shouldBlockResponse)
{
@@ -121,9 +121,10 @@ internal sealed class ScopedContentProcessor : IScopedContentProcessor
{
string messageId = message.MessageId ?? Guid.NewGuid().ToString();
ContentBase content = new PurviewTextContent(message.Text);
ProcessConversationMetadata conversationmetadata = new(content, messageId, false, $"Agent Framework Message {messageId}")
string correlationId = (sessionId ?? Guid.NewGuid().ToString()) + "@AF";
ProcessConversationMetadata conversationMetadata = new(content, messageId, false, $"Agent Framework Message {messageId}", correlationId)
{
CorrelationId = sessionId ?? Guid.NewGuid().ToString()
SequenceNumber = DateTime.UtcNow.Ticks,
};
ActivityMetadata activityMetadata = new(activity);
PolicyLocation policyLocation;
@@ -162,7 +163,7 @@ internal sealed class ScopedContentProcessor : IScopedContentProcessor
OperatingSystemVersion = "Unknown"
}
};
ContentToProcess contentToProcess = new([conversationmetadata], activityMetadata, deviceMetadata, integratedAppMetadata, protectedAppMetadata);
ContentToProcess contentToProcess = new([conversationMetadata], activityMetadata, deviceMetadata, integratedAppMetadata, protectedAppMetadata);
if (userId == null &&
tokenInfo?.UserId != null)
@@ -123,7 +123,7 @@ public sealed class AzureAgentProvider(Uri projectEndpoint, TokenCredential proj
IAsyncEnumerable<AgentResponseUpdate> agentResponse =
messages is not null ?
agent.RunStreamingAsync([.. messages], null, runOptions, cancellationToken) :
agent.RunStreamingAsync([new ChatMessage(ChatRole.User, string.Empty)], null, runOptions, cancellationToken);
agent.RunStreamingAsync([], null, runOptions, cancellationToken);
await foreach (AgentResponseUpdate update in agentResponse.ConfigureAwait(false))
{
@@ -1,7 +1,7 @@
// ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
// Runtime Version: 18.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
@@ -10,16 +10,13 @@
namespace Microsoft.Agents.AI.Workflows.Declarative.CodeGen
{
using Microsoft.Agents.AI.Workflows.Declarative.Extensions;
using Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
using Microsoft.Agents.ObjectModel;
using Microsoft.Extensions.AI;
using System.Collections.Generic;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "18.0.0.0")]
internal partial class AddConversationMessageTemplate : ActionTemplate
{
/// <summary>
@@ -35,17 +32,8 @@ namespace Microsoft.Agents.AI.Workflows.Declarative.CodeGen
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n\n/// <summary>\n/// Adds a new message to the specified agent conversation\n/// </" +
"summary>\ninternal sealed class ");
this.Write("\n/// <summary>\n/// Adds a new message to the specified agent conversation\n/// </s" +
"ummary>\ninternal sealed class ");
this.Write(this.ToStringHelper.ToStringWithCulture(this.Name));
this.Write("Executor(FormulaSession session, WorkflowAgentProvider agentProvider) : ActionExe" +
"cutor(id: \"");
@@ -134,446 +122,6 @@ this.Write("\n ");
}
void EvaluateBoolExpression(BoolExpression expression, string targetVariable, bool defaultValue = false)
{
if (expression is null)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatBoolValue(defaultValue)));
this.Write(";");
}
else if (expression.IsLiteral)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatBoolValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<bool>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<bool>>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<bool>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateEnumExpression<TWrapper, TValue>(
EnumExpression<TWrapper> expression,
string targetVariable,
IDictionary<TWrapper, string> resultMap,
string defaultValue = null,
bool qualifyResult = false,
bool isNullable = false)
where TWrapper : EnumWrapper
{
string resultType = $"{GetTypeAlias<TValue>()}{(isNullable ? "?" : "")}";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatValue<TValue>(defaultValue)));
this.Write(";");
}
else if (expression.IsLiteral)
{
resultMap.TryGetValue(expression.LiteralValue, out string resultValue);
if (qualifyResult)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(".");
this.Write(this.ToStringHelper.ToStringWithCulture(resultValue));
this.Write(";");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatValue<TValue>(resultValue)));
this.Write(";");
}
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateIntExpression(IntExpression expression, string targetVariable, bool isNullable = false)
{
string typeName = isNullable ? "int?" : "int";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(isNullable ? "null" : "0"));
this.Write(";");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.LiteralValue));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<int>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateListExpression<TElement>(ValueExpression expression, string targetVariable)
{
string typeName = GetTypeAlias<TElement>();
if (expression is null)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TElement>()));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write("> = await context.EvaluateListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateRecordExpression<TValue>(ObjectExpression<RecordDataValue> expression, string targetVariable)
{
string resultTypeName = $"Dictionary<string, {GetTypeAlias<TValue>()}?>?";
@@ -803,116 +351,6 @@ this.Write(").ConfigureAwait(false);");
}
void EvaluateValueExpression(ValueExpression expression, string targetVariable) =>
EvaluateValueExpression<object>(expression, targetVariable);
void EvaluateValueExpression<TValue>(ValueExpression expression, string targetVariable)
{
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateMessageTemplate(TemplateLine templateLine, string variableName)
{
if (templateLine is not null)
@@ -1,8 +1,12 @@
<#@ template language="C#" inherits="ActionTemplate" visibility="internal" linePragmas="false" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Core" #>
<#@ include file="Snippets/Index.tt" once="true" #>
<#@ import namespace="Microsoft.Agents.AI.Workflows.Declarative.Extensions" #>
<#@ import namespace="Microsoft.Agents.ObjectModel" #>
<#@ include file="Snippets/AssignVariableTemplate.tt" once="true" #>
<#@ include file="Snippets/EvaluateRecordExpressionTemplate.tt" once="true" #>
<#@ include file="Snippets/EvaluateStringExpressionTemplate.tt" once="true" #>
<#@ include file="Snippets/FormatMessageTemplate.tt" once="true" #>
/// <summary>
/// Adds a new message to the specified agent conversation
/// </summary>
@@ -9,11 +9,8 @@
// ------------------------------------------------------------------------------
namespace Microsoft.Agents.AI.Workflows.Declarative.CodeGen
{
using Microsoft.Agents.AI.Workflows.Declarative.Extensions;
using Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
using Microsoft.Agents.ObjectModel;
using Microsoft.Extensions.AI;
using System.Collections.Generic;
using Microsoft.Agents.ObjectModel;
using System;
/// <summary>
@@ -27,17 +24,6 @@ namespace Microsoft.Agents.AI.Workflows.Declarative.CodeGen
/// </summary>
public override string TransformText()
{
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
@@ -87,85 +73,6 @@ this.Write("\n ");
}
void EvaluateBoolExpression(BoolExpression expression, string targetVariable, bool defaultValue = false)
{
if (expression is null)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatBoolValue(defaultValue)));
this.Write(";");
}
else if (expression.IsLiteral)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatBoolValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<bool>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<bool>>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<bool>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateEnumExpression<TWrapper, TValue>(
EnumExpression<TWrapper> expression,
string targetVariable,
@@ -310,601 +217,5 @@ this.Write(").ConfigureAwait(false);");
}
}
void EvaluateIntExpression(IntExpression expression, string targetVariable, bool isNullable = false)
{
string typeName = isNullable ? "int?" : "int";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(isNullable ? "null" : "0"));
this.Write(";");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.LiteralValue));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<int>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateListExpression<TElement>(ValueExpression expression, string targetVariable)
{
string typeName = GetTypeAlias<TElement>();
if (expression is null)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TElement>()));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write("> = await context.EvaluateListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateRecordExpression<TValue>(ObjectExpression<RecordDataValue> expression, string targetVariable)
{
string resultTypeName = $"Dictionary<string, {GetTypeAlias<TValue>()}?>?";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" =\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateExpressionAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateExpressionAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateStringExpression(StringExpression expression, string targetVariable, bool isNullable = false)
{
string typeName = isNullable ? "string?" : "string";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(isNullable ? "null" : "string.Empty"));
this.Write(";");
}
else if (expression.IsLiteral)
{
if (expression.LiteralValue.Contains("\n"))
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = \n \"\"\"\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.LiteralValue));
this.Write("\n \"\"\";");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.LiteralValue)));
this.Write(";");
}
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<string>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<string>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<string>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateValueExpression(ValueExpression expression, string targetVariable) =>
EvaluateValueExpression<object>(expression, targetVariable);
void EvaluateValueExpression<TValue>(ValueExpression expression, string targetVariable)
{
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateMessageTemplate(TemplateLine templateLine, string variableName)
{
if (templateLine is not null)
{
this.Write("\n string ");
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
this.Write(" =\n await context.FormatTemplateAsync(\n \"\"\"");
FormatMessageTemplate(templateLine);
this.Write("\n \"\"\");");
}
else
{
this.Write("\n string? ");
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
this.Write(" = null;");
}
}
void FormatMessageTemplate(TemplateLine line)
{
foreach (string text in line.ToTemplateString().ByLine())
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(text));
}
}
}
}
@@ -1,7 +1,10 @@
<#@ template language="C#" inherits="ActionTemplate" visibility="internal" linePragmas="false" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Core" #>
<#@ include file="Snippets/Index.tt" once="true" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="Microsoft.Agents.ObjectModel" #>
<#@ include file="Snippets/AssignVariableTemplate.tt" once="true" #>
<#@ include file="Snippets/EvaluateEnumExpressionTemplate.tt" once="true" #>
/// <summary>
/// Reset all the state for the targeted variable scope.
/// </summary>
@@ -9,11 +9,8 @@
// ------------------------------------------------------------------------------
namespace Microsoft.Agents.AI.Workflows.Declarative.CodeGen
{
using Microsoft.Agents.AI.Workflows.Declarative.Extensions;
using Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
using Microsoft.Agents.ObjectModel;
using Microsoft.Extensions.AI;
using System.Collections.Generic;
using System;
/// <summary>
@@ -27,17 +24,6 @@ namespace Microsoft.Agents.AI.Workflows.Declarative.CodeGen
/// </summary>
public override string TransformText()
{
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
@@ -182,746 +168,5 @@ this.Write(").ConfigureAwait(false);");
}
}
void EvaluateEnumExpression<TWrapper, TValue>(
EnumExpression<TWrapper> expression,
string targetVariable,
IDictionary<TWrapper, string> resultMap,
string defaultValue = null,
bool qualifyResult = false,
bool isNullable = false)
where TWrapper : EnumWrapper
{
string resultType = $"{GetTypeAlias<TValue>()}{(isNullable ? "?" : "")}";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatValue<TValue>(defaultValue)));
this.Write(";");
}
else if (expression.IsLiteral)
{
resultMap.TryGetValue(expression.LiteralValue, out string resultValue);
if (qualifyResult)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(".");
this.Write(this.ToStringHelper.ToStringWithCulture(resultValue));
this.Write(";");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatValue<TValue>(resultValue)));
this.Write(";");
}
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateIntExpression(IntExpression expression, string targetVariable, bool isNullable = false)
{
string typeName = isNullable ? "int?" : "int";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(isNullable ? "null" : "0"));
this.Write(";");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.LiteralValue));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<int>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateListExpression<TElement>(ValueExpression expression, string targetVariable)
{
string typeName = GetTypeAlias<TElement>();
if (expression is null)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TElement>()));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write("> = await context.EvaluateListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateRecordExpression<TValue>(ObjectExpression<RecordDataValue> expression, string targetVariable)
{
string resultTypeName = $"Dictionary<string, {GetTypeAlias<TValue>()}?>?";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" =\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateExpressionAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateExpressionAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateStringExpression(StringExpression expression, string targetVariable, bool isNullable = false)
{
string typeName = isNullable ? "string?" : "string";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(isNullable ? "null" : "string.Empty"));
this.Write(";");
}
else if (expression.IsLiteral)
{
if (expression.LiteralValue.Contains("\n"))
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = \n \"\"\"\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.LiteralValue));
this.Write("\n \"\"\";");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.LiteralValue)));
this.Write(";");
}
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<string>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<string>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<string>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateValueExpression(ValueExpression expression, string targetVariable) =>
EvaluateValueExpression<object>(expression, targetVariable);
void EvaluateValueExpression<TValue>(ValueExpression expression, string targetVariable)
{
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateMessageTemplate(TemplateLine templateLine, string variableName)
{
if (templateLine is not null)
{
this.Write("\n string ");
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
this.Write(" =\n await context.FormatTemplateAsync(\n \"\"\"");
FormatMessageTemplate(templateLine);
this.Write("\n \"\"\");");
}
else
{
this.Write("\n string? ");
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
this.Write(" = null;");
}
}
void FormatMessageTemplate(TemplateLine line)
{
foreach (string text in line.ToTemplateString().ByLine())
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(text));
}
}
}
}
@@ -1,7 +1,10 @@
<#@ template language="C#" inherits="ActionTemplate" visibility="internal" linePragmas="false" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Core" #>
<#@ include file="Snippets/Index.tt" once="true" #>
<#@ import namespace="Microsoft.Agents.AI.Workflows.Declarative.ObjectModel" #>
<#@ import namespace="Microsoft.Agents.ObjectModel" #>
<#@ include file="Snippets/AssignVariableTemplate.tt" once="true" #>
<#@ include file="Snippets/EvaluateBoolExpressionTemplate.tt" once="true" #>
/// <summary>
/// Conditional branching similar to an if / elseif / elseif / else chain.
/// </summary>
@@ -1,7 +1,7 @@
// ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
// Runtime Version: 18.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
@@ -9,17 +9,14 @@
// ------------------------------------------------------------------------------
namespace Microsoft.Agents.AI.Workflows.Declarative.CodeGen
{
using Microsoft.Agents.AI.Workflows.Declarative.Extensions;
using Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
using Microsoft.Agents.ObjectModel;
using Microsoft.Extensions.AI;
using System.Collections.Generic;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "18.0.0.0")]
internal partial class CopyConversationMessagesTemplate : ActionTemplate
{
/// <summary>
@@ -27,16 +24,6 @@ namespace Microsoft.Agents.AI.Workflows.Declarative.CodeGen
/// </summary>
public override string TransformText()
{
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
@@ -103,554 +90,6 @@ this.Write("\n ");
}
void EvaluateBoolExpression(BoolExpression expression, string targetVariable, bool defaultValue = false)
{
if (expression is null)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatBoolValue(defaultValue)));
this.Write(";");
}
else if (expression.IsLiteral)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatBoolValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<bool>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<bool>>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<bool>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateEnumExpression<TWrapper, TValue>(
EnumExpression<TWrapper> expression,
string targetVariable,
IDictionary<TWrapper, string> resultMap,
string defaultValue = null,
bool qualifyResult = false,
bool isNullable = false)
where TWrapper : EnumWrapper
{
string resultType = $"{GetTypeAlias<TValue>()}{(isNullable ? "?" : "")}";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatValue<TValue>(defaultValue)));
this.Write(";");
}
else if (expression.IsLiteral)
{
resultMap.TryGetValue(expression.LiteralValue, out string resultValue);
if (qualifyResult)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(".");
this.Write(this.ToStringHelper.ToStringWithCulture(resultValue));
this.Write(";");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatValue<TValue>(resultValue)));
this.Write(";");
}
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateIntExpression(IntExpression expression, string targetVariable, bool isNullable = false)
{
string typeName = isNullable ? "int?" : "int";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(isNullable ? "null" : "0"));
this.Write(";");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.LiteralValue));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<int>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateListExpression<TElement>(ValueExpression expression, string targetVariable)
{
string typeName = GetTypeAlias<TElement>();
if (expression is null)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TElement>()));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write("> = await context.EvaluateListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateRecordExpression<TValue>(ObjectExpression<RecordDataValue> expression, string targetVariable)
{
string resultTypeName = $"Dictionary<string, {GetTypeAlias<TValue>()}?>?";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" =\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateExpressionAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateExpressionAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateStringExpression(StringExpression expression, string targetVariable, bool isNullable = false)
{
string typeName = isNullable ? "string?" : "string";
@@ -881,46 +320,5 @@ this.Write(").ConfigureAwait(false);");
}
}
void EvaluateMessageTemplate(TemplateLine templateLine, string variableName)
{
if (templateLine is not null)
{
this.Write("\n string ");
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
this.Write(" =\n await context.FormatTemplateAsync(\n \"\"\"");
FormatMessageTemplate(templateLine);
this.Write("\n \"\"\");");
}
else
{
this.Write("\n string? ");
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
this.Write(" = null;");
}
}
void FormatMessageTemplate(TemplateLine line)
{
foreach (string text in line.ToTemplateString().ByLine())
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(text));
}
}
}
}
@@ -1,7 +1,11 @@
<#@ template language="C#" inherits="ActionTemplate" visibility="internal" linePragmas="false" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Core" #>
<#@ include file="Snippets/Index.tt" once="true" #>
<#@ import namespace="Microsoft.Agents.ObjectModel" #>
<#@ import namespace="Microsoft.Extensions.AI" #>
<#@ include file="Snippets/AssignVariableTemplate.tt" once="true" #>
<#@ include file="Snippets/EvaluateStringExpressionTemplate.tt" once="true" #>
<#@ include file="Snippets/EvaluateValueExpressionTemplate.tt" once="true" #>
/// <summary>
/// Copies one or more messages into the specified agent conversation.
/// </summary>
@@ -1,7 +1,7 @@
// ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
// Runtime Version: 18.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
@@ -9,17 +9,13 @@
// ------------------------------------------------------------------------------
namespace Microsoft.Agents.AI.Workflows.Declarative.CodeGen
{
using Microsoft.Agents.AI.Workflows.Declarative.Extensions;
using Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
using Microsoft.Agents.ObjectModel;
using Microsoft.Extensions.AI;
using System.Collections.Generic;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "18.0.0.0")]
internal partial class CreateConversationTemplate : ActionTemplate
{
/// <summary>
@@ -27,19 +23,6 @@ namespace Microsoft.Agents.AI.Workflows.Declarative.CodeGen
/// </summary>
public override string TransformText()
{
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
@@ -91,825 +74,5 @@ this.Write("\n ");
}
}
void EvaluateBoolExpression(BoolExpression expression, string targetVariable, bool defaultValue = false)
{
if (expression is null)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatBoolValue(defaultValue)));
this.Write(";");
}
else if (expression.IsLiteral)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatBoolValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<bool>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<bool>>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<bool>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateEnumExpression<TWrapper, TValue>(
EnumExpression<TWrapper> expression,
string targetVariable,
IDictionary<TWrapper, string> resultMap,
string defaultValue = null,
bool qualifyResult = false,
bool isNullable = false)
where TWrapper : EnumWrapper
{
string resultType = $"{GetTypeAlias<TValue>()}{(isNullable ? "?" : "")}";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatValue<TValue>(defaultValue)));
this.Write(";");
}
else if (expression.IsLiteral)
{
resultMap.TryGetValue(expression.LiteralValue, out string resultValue);
if (qualifyResult)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(".");
this.Write(this.ToStringHelper.ToStringWithCulture(resultValue));
this.Write(";");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatValue<TValue>(resultValue)));
this.Write(";");
}
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateIntExpression(IntExpression expression, string targetVariable, bool isNullable = false)
{
string typeName = isNullable ? "int?" : "int";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(isNullable ? "null" : "0"));
this.Write(";");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.LiteralValue));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<int>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateListExpression<TElement>(ValueExpression expression, string targetVariable)
{
string typeName = GetTypeAlias<TElement>();
if (expression is null)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TElement>()));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write("> = await context.EvaluateListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateRecordExpression<TValue>(ObjectExpression<RecordDataValue> expression, string targetVariable)
{
string resultTypeName = $"Dictionary<string, {GetTypeAlias<TValue>()}?>?";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" =\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateExpressionAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateExpressionAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateStringExpression(StringExpression expression, string targetVariable, bool isNullable = false)
{
string typeName = isNullable ? "string?" : "string";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(isNullable ? "null" : "string.Empty"));
this.Write(";");
}
else if (expression.IsLiteral)
{
if (expression.LiteralValue.Contains("\n"))
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = \n \"\"\"\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.LiteralValue));
this.Write("\n \"\"\";");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.LiteralValue)));
this.Write(";");
}
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<string>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<string>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<string>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateValueExpression(ValueExpression expression, string targetVariable) =>
EvaluateValueExpression<object>(expression, targetVariable);
void EvaluateValueExpression<TValue>(ValueExpression expression, string targetVariable)
{
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateMessageTemplate(TemplateLine templateLine, string variableName)
{
if (templateLine is not null)
{
this.Write("\n string ");
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
this.Write(" =\n await context.FormatTemplateAsync(\n \"\"\"");
FormatMessageTemplate(templateLine);
this.Write("\n \"\"\");");
}
else
{
this.Write("\n string? ");
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
this.Write(" = null;");
}
}
void FormatMessageTemplate(TemplateLine line)
{
foreach (string text in line.ToTemplateString().ByLine())
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(text));
}
}
}
}
@@ -1,7 +1,8 @@
<#@ template language="C#" inherits="ActionTemplate" visibility="internal" linePragmas="false" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Core" #>
<#@ include file="Snippets/Index.tt" once="true" #>
<#@ import namespace="Microsoft.Agents.ObjectModel" #>
<#@ include file="Snippets/AssignVariableTemplate.tt" once="true" #>
/// <summary>
/// Creates a new conversation and stores the identifier value to the "<#= this.Model.ConversationId #>" variable.
/// </summary>
@@ -9,11 +9,6 @@
// ------------------------------------------------------------------------------
namespace Microsoft.Agents.AI.Workflows.Declarative.CodeGen
{
using Microsoft.Agents.AI.Workflows.Declarative.Extensions;
using Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
using Microsoft.Agents.ObjectModel;
using Microsoft.Extensions.AI;
using System.Collections.Generic;
using System;
/// <summary>
@@ -27,21 +22,6 @@ namespace Microsoft.Agents.AI.Workflows.Declarative.CodeGen
/// </summary>
public override string TransformText()
{
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n/// <summary>\n/// Modify items in a list\n/// </summary>\ninternal sealed class ");
@@ -53,853 +33,5 @@ namespace Microsoft.Agents.AI.Workflows.Declarative.CodeGen
" {\n return default;\n }\n}");
return this.GenerationEnvironment.ToString();
}
void AssignVariable(PropertyPath targetVariable, string valueVariable, bool tightFormat = false)
{
if (targetVariable is not null)
{
this.Write("\n await context.QueueStateUpdateAsync(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(VariableName(targetVariable)));
this.Write("\", value: ");
this.Write(this.ToStringHelper.ToStringWithCulture(valueVariable));
this.Write(", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(VariableScope(targetVariable)));
this.Write("\").ConfigureAwait(false);");
if (!tightFormat)
{
this.Write("\n ");
}
}
}
void EvaluateBoolExpression(BoolExpression expression, string targetVariable, bool defaultValue = false)
{
if (expression is null)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatBoolValue(defaultValue)));
this.Write(";");
}
else if (expression.IsLiteral)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatBoolValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<bool>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<bool>>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<bool>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateEnumExpression<TWrapper, TValue>(
EnumExpression<TWrapper> expression,
string targetVariable,
IDictionary<TWrapper, string> resultMap,
string defaultValue = null,
bool qualifyResult = false,
bool isNullable = false)
where TWrapper : EnumWrapper
{
string resultType = $"{GetTypeAlias<TValue>()}{(isNullable ? "?" : "")}";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatValue<TValue>(defaultValue)));
this.Write(";");
}
else if (expression.IsLiteral)
{
resultMap.TryGetValue(expression.LiteralValue, out string resultValue);
if (qualifyResult)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(".");
this.Write(this.ToStringHelper.ToStringWithCulture(resultValue));
this.Write(";");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatValue<TValue>(resultValue)));
this.Write(";");
}
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateIntExpression(IntExpression expression, string targetVariable, bool isNullable = false)
{
string typeName = isNullable ? "int?" : "int";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(isNullable ? "null" : "0"));
this.Write(";");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.LiteralValue));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<int>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateListExpression<TElement>(ValueExpression expression, string targetVariable)
{
string typeName = GetTypeAlias<TElement>();
if (expression is null)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TElement>()));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write("> = await context.EvaluateListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateRecordExpression<TValue>(ObjectExpression<RecordDataValue> expression, string targetVariable)
{
string resultTypeName = $"Dictionary<string, {GetTypeAlias<TValue>()}?>?";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" =\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateExpressionAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateExpressionAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateStringExpression(StringExpression expression, string targetVariable, bool isNullable = false)
{
string typeName = isNullable ? "string?" : "string";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(isNullable ? "null" : "string.Empty"));
this.Write(";");
}
else if (expression.IsLiteral)
{
if (expression.LiteralValue.Contains("\n"))
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = \n \"\"\"\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.LiteralValue));
this.Write("\n \"\"\";");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.LiteralValue)));
this.Write(";");
}
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<string>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<string>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<string>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateValueExpression(ValueExpression expression, string targetVariable) =>
EvaluateValueExpression<object>(expression, targetVariable);
void EvaluateValueExpression<TValue>(ValueExpression expression, string targetVariable)
{
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateMessageTemplate(TemplateLine templateLine, string variableName)
{
if (templateLine is not null)
{
this.Write("\n string ");
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
this.Write(" =\n await context.FormatTemplateAsync(\n \"\"\"");
FormatMessageTemplate(templateLine);
this.Write("\n \"\"\");");
}
else
{
this.Write("\n string? ");
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
this.Write(" = null;");
}
}
void FormatMessageTemplate(TemplateLine line)
{
foreach (string text in line.ToTemplateString().ByLine())
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(text));
}
}
}
}
@@ -1,7 +1,6 @@
<#@ template language="C#" inherits="ActionTemplate" visibility="internal" linePragmas="false" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Core" #>
<#@ include file="Snippets/Index.tt" once="true" #>
/// <summary>
/// Modify items in a list
/// </summary>
@@ -9,11 +9,7 @@
// ------------------------------------------------------------------------------
namespace Microsoft.Agents.AI.Workflows.Declarative.CodeGen
{
using Microsoft.Agents.AI.Workflows.Declarative.Extensions;
using Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
using Microsoft.Agents.ObjectModel;
using Microsoft.Extensions.AI;
using System.Collections.Generic;
using System;
/// <summary>
@@ -27,18 +23,6 @@ namespace Microsoft.Agents.AI.Workflows.Declarative.CodeGen
/// </summary>
public override string TransformText()
{
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
@@ -143,675 +127,6 @@ this.Write("\n ");
}
void EvaluateBoolExpression(BoolExpression expression, string targetVariable, bool defaultValue = false)
{
if (expression is null)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatBoolValue(defaultValue)));
this.Write(";");
}
else if (expression.IsLiteral)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatBoolValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<bool>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<bool>>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<bool>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateEnumExpression<TWrapper, TValue>(
EnumExpression<TWrapper> expression,
string targetVariable,
IDictionary<TWrapper, string> resultMap,
string defaultValue = null,
bool qualifyResult = false,
bool isNullable = false)
where TWrapper : EnumWrapper
{
string resultType = $"{GetTypeAlias<TValue>()}{(isNullable ? "?" : "")}";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatValue<TValue>(defaultValue)));
this.Write(";");
}
else if (expression.IsLiteral)
{
resultMap.TryGetValue(expression.LiteralValue, out string resultValue);
if (qualifyResult)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(".");
this.Write(this.ToStringHelper.ToStringWithCulture(resultValue));
this.Write(";");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatValue<TValue>(resultValue)));
this.Write(";");
}
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateIntExpression(IntExpression expression, string targetVariable, bool isNullable = false)
{
string typeName = isNullable ? "int?" : "int";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(isNullable ? "null" : "0"));
this.Write(";");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.LiteralValue));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<int>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateListExpression<TElement>(ValueExpression expression, string targetVariable)
{
string typeName = GetTypeAlias<TElement>();
if (expression is null)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TElement>()));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write("> = await context.EvaluateListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateRecordExpression<TValue>(ObjectExpression<RecordDataValue> expression, string targetVariable)
{
string resultTypeName = $"Dictionary<string, {GetTypeAlias<TValue>()}?>?";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" =\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateExpressionAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateExpressionAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateStringExpression(StringExpression expression, string targetVariable, bool isNullable = false)
{
string typeName = isNullable ? "string?" : "string";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(isNullable ? "null" : "string.Empty"));
this.Write(";");
}
else if (expression.IsLiteral)
{
if (expression.LiteralValue.Contains("\n"))
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = \n \"\"\"\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.LiteralValue));
this.Write("\n \"\"\";");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.LiteralValue)));
this.Write(";");
}
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<string>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<string>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<string>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateValueExpression(ValueExpression expression, string targetVariable) =>
EvaluateValueExpression<object>(expression, targetVariable);
@@ -921,46 +236,5 @@ this.Write(").ConfigureAwait(false);");
}
}
void EvaluateMessageTemplate(TemplateLine templateLine, string variableName)
{
if (templateLine is not null)
{
this.Write("\n string ");
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
this.Write(" =\n await context.FormatTemplateAsync(\n \"\"\"");
FormatMessageTemplate(templateLine);
this.Write("\n \"\"\");");
}
else
{
this.Write("\n string? ");
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
this.Write(" = null;");
}
}
void FormatMessageTemplate(TemplateLine line)
{
foreach (string text in line.ToTemplateString().ByLine())
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(text));
}
}
}
}
@@ -1,7 +1,9 @@
<#@ template language="C#" inherits="ActionTemplate" visibility="internal" linePragmas="false" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Core" #>
<#@ include file="Snippets/Index.tt" once="true" #>
<#@ import namespace="Microsoft.Agents.ObjectModel" #>
<#@ include file="Snippets/AssignVariableTemplate.tt" once="true" #>
<#@ include file="Snippets/EvaluateValueExpressionTemplate.tt" once="true" #>
/// <summary>
/// Loops over a list assignign the loop variable to "<#= this.Model.Value #>" variable.
/// </summary>
@@ -1,7 +1,7 @@
// ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
// Runtime Version: 18.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
@@ -9,17 +9,16 @@
// ------------------------------------------------------------------------------
namespace Microsoft.Agents.AI.Workflows.Declarative.CodeGen
{
using System.Collections.Generic;
using Microsoft.Agents.AI.Workflows.Declarative.Extensions;
using Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
using Microsoft.Agents.ObjectModel;
using Microsoft.Extensions.AI;
using System.Collections.Generic;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "18.0.0.0")]
internal partial class InvokeAzureAgentTemplate : ActionTemplate
{
/// <summary>
@@ -37,13 +36,6 @@ namespace Microsoft.Agents.AI.Workflows.Declarative.CodeGen
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n/// <summary>\n/// Invokes an agent to process messages and return a response wit" +
"hin a conversation context.\n/// </summary>\ninternal sealed class ");
this.Write(this.ToStringHelper.ToStringWithCulture(this.Name));
@@ -191,259 +183,6 @@ this.Write(").ConfigureAwait(false);");
}
void EvaluateEnumExpression<TWrapper, TValue>(
EnumExpression<TWrapper> expression,
string targetVariable,
IDictionary<TWrapper, string> resultMap,
string defaultValue = null,
bool qualifyResult = false,
bool isNullable = false)
where TWrapper : EnumWrapper
{
string resultType = $"{GetTypeAlias<TValue>()}{(isNullable ? "?" : "")}";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatValue<TValue>(defaultValue)));
this.Write(";");
}
else if (expression.IsLiteral)
{
resultMap.TryGetValue(expression.LiteralValue, out string resultValue);
if (qualifyResult)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(".");
this.Write(this.ToStringHelper.ToStringWithCulture(resultValue));
this.Write(";");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatValue<TValue>(resultValue)));
this.Write(";");
}
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateIntExpression(IntExpression expression, string targetVariable, bool isNullable = false)
{
string typeName = isNullable ? "int?" : "int";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(isNullable ? "null" : "0"));
this.Write(";");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.LiteralValue));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<int>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateListExpression<TElement>(ValueExpression expression, string targetVariable)
{
string typeName = GetTypeAlias<TElement>();
@@ -552,114 +291,6 @@ this.Write(").ConfigureAwait(false);");
}
void EvaluateRecordExpression<TValue>(ObjectExpression<RecordDataValue> expression, string targetVariable)
{
string resultTypeName = $"Dictionary<string, {GetTypeAlias<TValue>()}?>?";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" =\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateExpressionAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateExpressionAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateStringExpression(StringExpression expression, string targetVariable, bool isNullable = false)
{
string typeName = isNullable ? "string?" : "string";
@@ -780,156 +411,5 @@ this.Write(").ConfigureAwait(false);");
}
}
void EvaluateValueExpression(ValueExpression expression, string targetVariable) =>
EvaluateValueExpression<object>(expression, targetVariable);
void EvaluateValueExpression<TValue>(ValueExpression expression, string targetVariable)
{
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateMessageTemplate(TemplateLine templateLine, string variableName)
{
if (templateLine is not null)
{
this.Write("\n string ");
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
this.Write(" =\n await context.FormatTemplateAsync(\n \"\"\"");
FormatMessageTemplate(templateLine);
this.Write("\n \"\"\");");
}
else
{
this.Write("\n string? ");
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
this.Write(" = null;");
}
}
void FormatMessageTemplate(TemplateLine line)
{
foreach (string text in line.ToTemplateString().ByLine())
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(text));
}
}
}
}
@@ -1,7 +1,14 @@
<#@ template language="C#" inherits="ActionTemplate" visibility="internal" linePragmas="false" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Core" #>
<#@ include file="Snippets/Index.tt" once="true" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="Microsoft.Agents.AI.Workflows.Declarative.Extensions" #>
<#@ import namespace="Microsoft.Agents.ObjectModel" #>
<#@ import namespace="Microsoft.Extensions.AI" #>
<#@ include file="Snippets/AssignVariableTemplate.tt" once="true" #>
<#@ include file="Snippets/EvaluateBoolExpressionTemplate.tt" once="true" #>
<#@ include file="Snippets/EvaluateListExpressionTemplate.tt" once="true" #>
<#@ include file="Snippets/EvaluateStringExpressionTemplate.tt" once="true" #>
/// <summary>
/// Invokes an agent to process messages and return a response within a conversation context.
/// </summary>
@@ -9,11 +9,7 @@
// ------------------------------------------------------------------------------
namespace Microsoft.Agents.AI.Workflows.Declarative.CodeGen
{
using Microsoft.Agents.AI.Workflows.Declarative.Extensions;
using Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
using Microsoft.Agents.ObjectModel;
using Microsoft.Extensions.AI;
using System.Collections.Generic;
using System;
/// <summary>
@@ -27,19 +23,6 @@ namespace Microsoft.Agents.AI.Workflows.Declarative.CodeGen
/// </summary>
public override string TransformText()
{
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
@@ -112,825 +95,5 @@ this.Write("\n ");
}
}
void EvaluateBoolExpression(BoolExpression expression, string targetVariable, bool defaultValue = false)
{
if (expression is null)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatBoolValue(defaultValue)));
this.Write(";");
}
else if (expression.IsLiteral)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatBoolValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<bool>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<bool>>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<bool>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateEnumExpression<TWrapper, TValue>(
EnumExpression<TWrapper> expression,
string targetVariable,
IDictionary<TWrapper, string> resultMap,
string defaultValue = null,
bool qualifyResult = false,
bool isNullable = false)
where TWrapper : EnumWrapper
{
string resultType = $"{GetTypeAlias<TValue>()}{(isNullable ? "?" : "")}";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatValue<TValue>(defaultValue)));
this.Write(";");
}
else if (expression.IsLiteral)
{
resultMap.TryGetValue(expression.LiteralValue, out string resultValue);
if (qualifyResult)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(".");
this.Write(this.ToStringHelper.ToStringWithCulture(resultValue));
this.Write(";");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatValue<TValue>(resultValue)));
this.Write(";");
}
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateIntExpression(IntExpression expression, string targetVariable, bool isNullable = false)
{
string typeName = isNullable ? "int?" : "int";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(isNullable ? "null" : "0"));
this.Write(";");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.LiteralValue));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<int>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateListExpression<TElement>(ValueExpression expression, string targetVariable)
{
string typeName = GetTypeAlias<TElement>();
if (expression is null)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TElement>()));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write("> = await context.EvaluateListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateRecordExpression<TValue>(ObjectExpression<RecordDataValue> expression, string targetVariable)
{
string resultTypeName = $"Dictionary<string, {GetTypeAlias<TValue>()}?>?";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" =\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateExpressionAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateExpressionAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateStringExpression(StringExpression expression, string targetVariable, bool isNullable = false)
{
string typeName = isNullable ? "string?" : "string";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(isNullable ? "null" : "string.Empty"));
this.Write(";");
}
else if (expression.IsLiteral)
{
if (expression.LiteralValue.Contains("\n"))
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = \n \"\"\"\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.LiteralValue));
this.Write("\n \"\"\";");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.LiteralValue)));
this.Write(";");
}
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<string>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<string>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<string>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateValueExpression(ValueExpression expression, string targetVariable) =>
EvaluateValueExpression<object>(expression, targetVariable);
void EvaluateValueExpression<TValue>(ValueExpression expression, string targetVariable)
{
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateMessageTemplate(TemplateLine templateLine, string variableName)
{
if (templateLine is not null)
{
this.Write("\n string ");
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
this.Write(" =\n await context.FormatTemplateAsync(\n \"\"\"");
FormatMessageTemplate(templateLine);
this.Write("\n \"\"\");");
}
else
{
this.Write("\n string? ");
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
this.Write(" = null;");
}
}
void FormatMessageTemplate(TemplateLine line)
{
foreach (string text in line.ToTemplateString().ByLine())
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(text));
}
}
}
}
@@ -1,7 +1,8 @@
<#@ template language="C#" inherits="ActionTemplate" visibility="internal" linePragmas="false" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Core" #>
<#@ include file="Snippets/Index.tt" once="true" #>
<#@ import namespace="Microsoft.Agents.ObjectModel" #>
<#@ include file="Snippets/AssignVariableTemplate.tt" once="true" #>
/// <summary>
/// Parses a string or untyped value to the provided data type. When the input is a string, it will be treated as JSON.
/// </summary>
@@ -9,11 +9,6 @@
// ------------------------------------------------------------------------------
namespace Microsoft.Agents.AI.Workflows.Declarative.CodeGen
{
using Microsoft.Agents.AI.Workflows.Declarative.Extensions;
using Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
using Microsoft.Agents.ObjectModel;
using Microsoft.Extensions.AI;
using System.Collections.Generic;
using System;
/// <summary>
@@ -27,21 +22,6 @@ namespace Microsoft.Agents.AI.Workflows.Declarative.CodeGen
/// </summary>
public override string TransformText()
{
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n/// <summary>\n/// Request input.\n/// </summary>\ninternal sealed class ");
@@ -53,853 +33,5 @@ namespace Microsoft.Agents.AI.Workflows.Declarative.CodeGen
" {\n return default;\n }\n}");
return this.GenerationEnvironment.ToString();
}
void AssignVariable(PropertyPath targetVariable, string valueVariable, bool tightFormat = false)
{
if (targetVariable is not null)
{
this.Write("\n await context.QueueStateUpdateAsync(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(VariableName(targetVariable)));
this.Write("\", value: ");
this.Write(this.ToStringHelper.ToStringWithCulture(valueVariable));
this.Write(", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(VariableScope(targetVariable)));
this.Write("\").ConfigureAwait(false);");
if (!tightFormat)
{
this.Write("\n ");
}
}
}
void EvaluateBoolExpression(BoolExpression expression, string targetVariable, bool defaultValue = false)
{
if (expression is null)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatBoolValue(defaultValue)));
this.Write(";");
}
else if (expression.IsLiteral)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatBoolValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<bool>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<bool>>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<bool>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateEnumExpression<TWrapper, TValue>(
EnumExpression<TWrapper> expression,
string targetVariable,
IDictionary<TWrapper, string> resultMap,
string defaultValue = null,
bool qualifyResult = false,
bool isNullable = false)
where TWrapper : EnumWrapper
{
string resultType = $"{GetTypeAlias<TValue>()}{(isNullable ? "?" : "")}";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatValue<TValue>(defaultValue)));
this.Write(";");
}
else if (expression.IsLiteral)
{
resultMap.TryGetValue(expression.LiteralValue, out string resultValue);
if (qualifyResult)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(".");
this.Write(this.ToStringHelper.ToStringWithCulture(resultValue));
this.Write(";");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatValue<TValue>(resultValue)));
this.Write(";");
}
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateIntExpression(IntExpression expression, string targetVariable, bool isNullable = false)
{
string typeName = isNullable ? "int?" : "int";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(isNullable ? "null" : "0"));
this.Write(";");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.LiteralValue));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<int>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateListExpression<TElement>(ValueExpression expression, string targetVariable)
{
string typeName = GetTypeAlias<TElement>();
if (expression is null)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TElement>()));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write("> = await context.EvaluateListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateRecordExpression<TValue>(ObjectExpression<RecordDataValue> expression, string targetVariable)
{
string resultTypeName = $"Dictionary<string, {GetTypeAlias<TValue>()}?>?";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" =\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateExpressionAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateExpressionAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateStringExpression(StringExpression expression, string targetVariable, bool isNullable = false)
{
string typeName = isNullable ? "string?" : "string";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(isNullable ? "null" : "string.Empty"));
this.Write(";");
}
else if (expression.IsLiteral)
{
if (expression.LiteralValue.Contains("\n"))
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = \n \"\"\"\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.LiteralValue));
this.Write("\n \"\"\";");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.LiteralValue)));
this.Write(";");
}
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<string>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<string>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<string>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateValueExpression(ValueExpression expression, string targetVariable) =>
EvaluateValueExpression<object>(expression, targetVariable);
void EvaluateValueExpression<TValue>(ValueExpression expression, string targetVariable)
{
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateMessageTemplate(TemplateLine templateLine, string variableName)
{
if (templateLine is not null)
{
this.Write("\n string ");
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
this.Write(" =\n await context.FormatTemplateAsync(\n \"\"\"");
FormatMessageTemplate(templateLine);
this.Write("\n \"\"\");");
}
else
{
this.Write("\n string? ");
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
this.Write(" = null;");
}
}
void FormatMessageTemplate(TemplateLine line)
{
foreach (string text in line.ToTemplateString().ByLine())
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(text));
}
}
}
}
@@ -1,7 +1,6 @@
<#@ template language="C#" inherits="ActionTemplate" visibility="internal" linePragmas="false" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Core" #>
<#@ include file="Snippets/Index.tt" once="true" #>
/// <summary>
/// Request input.
/// </summary>
@@ -9,11 +9,7 @@
// ------------------------------------------------------------------------------
namespace Microsoft.Agents.AI.Workflows.Declarative.CodeGen
{
using Microsoft.Agents.AI.Workflows.Declarative.Extensions;
using Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
using Microsoft.Agents.ObjectModel;
using Microsoft.Extensions.AI;
using System.Collections.Generic;
using System;
/// <summary>
@@ -27,19 +23,6 @@ namespace Microsoft.Agents.AI.Workflows.Declarative.CodeGen
/// </summary>
public override string TransformText()
{
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
@@ -87,825 +70,5 @@ this.Write("\n ");
}
}
void EvaluateBoolExpression(BoolExpression expression, string targetVariable, bool defaultValue = false)
{
if (expression is null)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatBoolValue(defaultValue)));
this.Write(";");
}
else if (expression.IsLiteral)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatBoolValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<bool>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<bool>>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<bool>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateEnumExpression<TWrapper, TValue>(
EnumExpression<TWrapper> expression,
string targetVariable,
IDictionary<TWrapper, string> resultMap,
string defaultValue = null,
bool qualifyResult = false,
bool isNullable = false)
where TWrapper : EnumWrapper
{
string resultType = $"{GetTypeAlias<TValue>()}{(isNullable ? "?" : "")}";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatValue<TValue>(defaultValue)));
this.Write(";");
}
else if (expression.IsLiteral)
{
resultMap.TryGetValue(expression.LiteralValue, out string resultValue);
if (qualifyResult)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(".");
this.Write(this.ToStringHelper.ToStringWithCulture(resultValue));
this.Write(";");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatValue<TValue>(resultValue)));
this.Write(";");
}
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateIntExpression(IntExpression expression, string targetVariable, bool isNullable = false)
{
string typeName = isNullable ? "int?" : "int";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(isNullable ? "null" : "0"));
this.Write(";");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.LiteralValue));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<int>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateListExpression<TElement>(ValueExpression expression, string targetVariable)
{
string typeName = GetTypeAlias<TElement>();
if (expression is null)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TElement>()));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write("> = await context.EvaluateListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateRecordExpression<TValue>(ObjectExpression<RecordDataValue> expression, string targetVariable)
{
string resultTypeName = $"Dictionary<string, {GetTypeAlias<TValue>()}?>?";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" =\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateExpressionAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateExpressionAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateStringExpression(StringExpression expression, string targetVariable, bool isNullable = false)
{
string typeName = isNullable ? "string?" : "string";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(isNullable ? "null" : "string.Empty"));
this.Write(";");
}
else if (expression.IsLiteral)
{
if (expression.LiteralValue.Contains("\n"))
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = \n \"\"\"\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.LiteralValue));
this.Write("\n \"\"\";");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.LiteralValue)));
this.Write(";");
}
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<string>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<string>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<string>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateValueExpression(ValueExpression expression, string targetVariable) =>
EvaluateValueExpression<object>(expression, targetVariable);
void EvaluateValueExpression<TValue>(ValueExpression expression, string targetVariable)
{
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateMessageTemplate(TemplateLine templateLine, string variableName)
{
if (templateLine is not null)
{
this.Write("\n string ");
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
this.Write(" =\n await context.FormatTemplateAsync(\n \"\"\"");
FormatMessageTemplate(templateLine);
this.Write("\n \"\"\");");
}
else
{
this.Write("\n string? ");
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
this.Write(" = null;");
}
}
void FormatMessageTemplate(TemplateLine line)
{
foreach (string text in line.ToTemplateString().ByLine())
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(text));
}
}
}
}
@@ -1,7 +1,8 @@
<#@ template language="C#" inherits="ActionTemplate" visibility="internal" linePragmas="false" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Core" #>
<#@ include file="Snippets/Index.tt" once="true" #>
<#@ import namespace="Microsoft.Agents.ObjectModel" #>
<#@ include file="Snippets/AssignVariableTemplate.tt" once="true" #>
/// <summary>
/// Resets the value of the "<#= this.Model.Variable #>" variable, potentially causing re-evaluation
/// of the default value, question or action that provides the value to this variable.
@@ -9,11 +9,7 @@
// ------------------------------------------------------------------------------
namespace Microsoft.Agents.AI.Workflows.Declarative.CodeGen
{
using Microsoft.Agents.AI.Workflows.Declarative.Extensions;
using Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
using Microsoft.Agents.ObjectModel;
using Microsoft.Extensions.AI;
using System.Collections.Generic;
using System;
/// <summary>
@@ -27,17 +23,6 @@ namespace Microsoft.Agents.AI.Workflows.Declarative.CodeGen
/// </summary>
public override string TransformText()
{
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
@@ -93,446 +78,6 @@ this.Write("\n ");
}
void EvaluateBoolExpression(BoolExpression expression, string targetVariable, bool defaultValue = false)
{
if (expression is null)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatBoolValue(defaultValue)));
this.Write(";");
}
else if (expression.IsLiteral)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatBoolValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<bool>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<bool>>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<bool>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateEnumExpression<TWrapper, TValue>(
EnumExpression<TWrapper> expression,
string targetVariable,
IDictionary<TWrapper, string> resultMap,
string defaultValue = null,
bool qualifyResult = false,
bool isNullable = false)
where TWrapper : EnumWrapper
{
string resultType = $"{GetTypeAlias<TValue>()}{(isNullable ? "?" : "")}";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatValue<TValue>(defaultValue)));
this.Write(";");
}
else if (expression.IsLiteral)
{
resultMap.TryGetValue(expression.LiteralValue, out string resultValue);
if (qualifyResult)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(".");
this.Write(this.ToStringHelper.ToStringWithCulture(resultValue));
this.Write(";");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatValue<TValue>(resultValue)));
this.Write(";");
}
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateIntExpression(IntExpression expression, string targetVariable, bool isNullable = false)
{
string typeName = isNullable ? "int?" : "int";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(isNullable ? "null" : "0"));
this.Write(";");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.LiteralValue));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<int>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateListExpression<TElement>(ValueExpression expression, string targetVariable)
{
string typeName = GetTypeAlias<TElement>();
if (expression is null)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TElement>()));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write("> = await context.EvaluateListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateRecordExpression<TValue>(ObjectExpression<RecordDataValue> expression, string targetVariable)
{
string resultTypeName = $"Dictionary<string, {GetTypeAlias<TValue>()}?>?";
@@ -761,156 +306,5 @@ this.Write(").ConfigureAwait(false);");
}
}
void EvaluateValueExpression(ValueExpression expression, string targetVariable) =>
EvaluateValueExpression<object>(expression, targetVariable);
void EvaluateValueExpression<TValue>(ValueExpression expression, string targetVariable)
{
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateMessageTemplate(TemplateLine templateLine, string variableName)
{
if (templateLine is not null)
{
this.Write("\n string ");
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
this.Write(" =\n await context.FormatTemplateAsync(\n \"\"\"");
FormatMessageTemplate(templateLine);
this.Write("\n \"\"\");");
}
else
{
this.Write("\n string? ");
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
this.Write(" = null;");
}
}
void FormatMessageTemplate(TemplateLine line)
{
foreach (string text in line.ToTemplateString().ByLine())
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(text));
}
}
}
}
@@ -1,7 +1,10 @@
<#@ template language="C#" inherits="ActionTemplate" visibility="internal" linePragmas="false" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Core" #>
<#@ include file="Snippets/Index.tt" once="true" #>
<#@ import namespace="Microsoft.Agents.ObjectModel" #>
<#@ include file="Snippets/AssignVariableTemplate.tt" once="true" #>
<#@ include file="Snippets/EvaluateRecordExpressionTemplate.tt" once="true" #>
<#@ include file="Snippets/EvaluateStringExpressionTemplate.tt" once="true" #>
/// <summary>
/// Retrieves a list of messages from an agent conversation.
/// </summary>
@@ -1,7 +1,7 @@
// ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
// Runtime Version: 18.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
@@ -9,17 +9,15 @@
// ------------------------------------------------------------------------------
namespace Microsoft.Agents.AI.Workflows.Declarative.CodeGen
{
using Microsoft.Agents.AI.Workflows.Declarative.Extensions;
using Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
using Microsoft.Agents.ObjectModel;
using Microsoft.Extensions.AI;
using System.Collections.Generic;
using Microsoft.Agents.AI.Workflows.Declarative.Extensions;
using Microsoft.Agents.ObjectModel;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "18.0.0.0")]
internal partial class RetrieveConversationMessagesTemplate : ActionTemplate
{
/// <summary>
@@ -37,13 +35,6 @@ namespace Microsoft.Agents.AI.Workflows.Declarative.CodeGen
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n/// <summary>\n/// Retrieves a specific message from an agent conversation.\n/// <" +
"/summary>\ninternal sealed class ");
this.Write(this.ToStringHelper.ToStringWithCulture(this.Name));
@@ -108,85 +99,6 @@ this.Write("\n ");
}
void EvaluateBoolExpression(BoolExpression expression, string targetVariable, bool defaultValue = false)
{
if (expression is null)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatBoolValue(defaultValue)));
this.Write(";");
}
else if (expression.IsLiteral)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatBoolValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<bool>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<bool>>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<bool>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateEnumExpression<TWrapper, TValue>(
EnumExpression<TWrapper> expression,
string targetVariable,
@@ -440,114 +352,6 @@ this.Write(").ConfigureAwait(false);");
}
void EvaluateListExpression<TElement>(ValueExpression expression, string targetVariable)
{
string typeName = GetTypeAlias<TElement>();
if (expression is null)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TElement>()));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write("> = await context.EvaluateListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateRecordExpression<TValue>(ObjectExpression<RecordDataValue> expression, string targetVariable)
{
string resultTypeName = $"Dictionary<string, {GetTypeAlias<TValue>()}?>?";
@@ -776,156 +580,5 @@ this.Write(").ConfigureAwait(false);");
}
}
void EvaluateValueExpression(ValueExpression expression, string targetVariable) =>
EvaluateValueExpression<object>(expression, targetVariable);
void EvaluateValueExpression<TValue>(ValueExpression expression, string targetVariable)
{
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateMessageTemplate(TemplateLine templateLine, string variableName)
{
if (templateLine is not null)
{
this.Write("\n string ");
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
this.Write(" =\n await context.FormatTemplateAsync(\n \"\"\"");
FormatMessageTemplate(templateLine);
this.Write("\n \"\"\");");
}
else
{
this.Write("\n string? ");
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
this.Write(" = null;");
}
}
void FormatMessageTemplate(TemplateLine line)
{
foreach (string text in line.ToTemplateString().ByLine())
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(text));
}
}
}
}
@@ -1,7 +1,14 @@
<#@ template language="C#" inherits="ActionTemplate" visibility="internal" linePragmas="false" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Core" #>
<#@ include file="Snippets/Index.tt" once="true" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="Microsoft.Agents.AI.Workflows.Declarative.Extensions" #>
<#@ import namespace="Microsoft.Agents.ObjectModel" #>
<#@ include file="Snippets/AssignVariableTemplate.tt" once="true" #>
<#@ include file="Snippets/EvaluateEnumExpressionTemplate.tt" once="true" #>
<#@ include file="Snippets/EvaluateIntExpressionTemplate.tt" once="true" #>
<#@ include file="Snippets/EvaluateRecordExpressionTemplate.tt" once="true" #>
<#@ include file="Snippets/EvaluateStringExpressionTemplate.tt" once="true" #>
/// <summary>
/// Retrieves a specific message from an agent conversation.
/// </summary>
@@ -10,10 +10,7 @@
namespace Microsoft.Agents.AI.Workflows.Declarative.CodeGen
{
using Microsoft.Agents.AI.Workflows.Declarative.Extensions;
using Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
using Microsoft.Agents.ObjectModel;
using Microsoft.Extensions.AI;
using System.Collections.Generic;
using System;
/// <summary>
@@ -27,18 +24,6 @@ namespace Microsoft.Agents.AI.Workflows.Declarative.CodeGen
/// </summary>
public override string TransformText()
{
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
@@ -71,822 +56,15 @@ if (this.Model.Activity is MessageActivityTemplate messageActivity)
}
this.Write("\n );\n AgentResponse response = new([new ChatMessage(ChatRole" +
".Assistant, activityText)]);\n await context.AddEventAsync(new AgentRes" +
"ponseEvent(this.Id, response)).ConfigureAwait(false);");
this.Write("\n );\n AgentResponse response = new([new ChatMessage(ChatRole.As" +
"sistant, activityText)]);\n await context.AddEventAsync(new AgentResponseE" +
"vent(this.Id, response)).ConfigureAwait(false);");
}
this.Write("\n\n return default;\n }\n}");
return this.GenerationEnvironment.ToString();
}
void AssignVariable(PropertyPath targetVariable, string valueVariable, bool tightFormat = false)
{
if (targetVariable is not null)
{
this.Write("\n await context.QueueStateUpdateAsync(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(VariableName(targetVariable)));
this.Write("\", value: ");
this.Write(this.ToStringHelper.ToStringWithCulture(valueVariable));
this.Write(", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(VariableScope(targetVariable)));
this.Write("\").ConfigureAwait(false);");
if (!tightFormat)
{
this.Write("\n ");
}
}
}
void EvaluateBoolExpression(BoolExpression expression, string targetVariable, bool defaultValue = false)
{
if (expression is null)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatBoolValue(defaultValue)));
this.Write(";");
}
else if (expression.IsLiteral)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatBoolValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<bool>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<bool>>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<bool>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateEnumExpression<TWrapper, TValue>(
EnumExpression<TWrapper> expression,
string targetVariable,
IDictionary<TWrapper, string> resultMap,
string defaultValue = null,
bool qualifyResult = false,
bool isNullable = false)
where TWrapper : EnumWrapper
{
string resultType = $"{GetTypeAlias<TValue>()}{(isNullable ? "?" : "")}";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatValue<TValue>(defaultValue)));
this.Write(";");
}
else if (expression.IsLiteral)
{
resultMap.TryGetValue(expression.LiteralValue, out string resultValue);
if (qualifyResult)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(".");
this.Write(this.ToStringHelper.ToStringWithCulture(resultValue));
this.Write(";");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatValue<TValue>(resultValue)));
this.Write(";");
}
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateIntExpression(IntExpression expression, string targetVariable, bool isNullable = false)
{
string typeName = isNullable ? "int?" : "int";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(isNullable ? "null" : "0"));
this.Write(";");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.LiteralValue));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<int>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateListExpression<TElement>(ValueExpression expression, string targetVariable)
{
string typeName = GetTypeAlias<TElement>();
if (expression is null)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TElement>()));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write("> = await context.EvaluateListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateRecordExpression<TValue>(ObjectExpression<RecordDataValue> expression, string targetVariable)
{
string resultTypeName = $"Dictionary<string, {GetTypeAlias<TValue>()}?>?";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" =\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateExpressionAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateExpressionAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateStringExpression(StringExpression expression, string targetVariable, bool isNullable = false)
{
string typeName = isNullable ? "string?" : "string";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(isNullable ? "null" : "string.Empty"));
this.Write(";");
}
else if (expression.IsLiteral)
{
if (expression.LiteralValue.Contains("\n"))
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = \n \"\"\"\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.LiteralValue));
this.Write("\n \"\"\";");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.LiteralValue)));
this.Write(";");
}
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<string>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<string>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<string>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateValueExpression(ValueExpression expression, string targetVariable) =>
EvaluateValueExpression<object>(expression, targetVariable);
void EvaluateValueExpression<TValue>(ValueExpression expression, string targetVariable)
{
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateMessageTemplate(TemplateLine templateLine, string variableName)
{
if (templateLine is not null)
@@ -1,7 +1,9 @@
<#@ template language="C#" inherits="ActionTemplate" visibility="internal" linePragmas="false" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Core" #>
<#@ include file="Snippets/Index.tt" once="true" #>
<#@ import namespace="Microsoft.Agents.AI.Workflows.Declarative.Extensions" #>
<#@ import namespace="Microsoft.Agents.ObjectModel" #>
<#@ include file="Snippets/FormatMessageTemplate.tt" once="true" #>
/// <summary>
/// Formats a message template and sends an activity event.
/// </summary>
@@ -9,11 +9,7 @@
// ------------------------------------------------------------------------------
namespace Microsoft.Agents.AI.Workflows.Declarative.CodeGen
{
using Microsoft.Agents.AI.Workflows.Declarative.Extensions;
using Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
using Microsoft.Agents.ObjectModel;
using Microsoft.Extensions.AI;
using System.Collections.Generic;
using System;
/// <summary>
@@ -27,18 +23,6 @@ namespace Microsoft.Agents.AI.Workflows.Declarative.CodeGen
/// </summary>
public override string TransformText()
{
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
@@ -98,675 +82,6 @@ this.Write("\n ");
}
void EvaluateBoolExpression(BoolExpression expression, string targetVariable, bool defaultValue = false)
{
if (expression is null)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatBoolValue(defaultValue)));
this.Write(";");
}
else if (expression.IsLiteral)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatBoolValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<bool>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<bool>>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<bool>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateEnumExpression<TWrapper, TValue>(
EnumExpression<TWrapper> expression,
string targetVariable,
IDictionary<TWrapper, string> resultMap,
string defaultValue = null,
bool qualifyResult = false,
bool isNullable = false)
where TWrapper : EnumWrapper
{
string resultType = $"{GetTypeAlias<TValue>()}{(isNullable ? "?" : "")}";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatValue<TValue>(defaultValue)));
this.Write(";");
}
else if (expression.IsLiteral)
{
resultMap.TryGetValue(expression.LiteralValue, out string resultValue);
if (qualifyResult)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(".");
this.Write(this.ToStringHelper.ToStringWithCulture(resultValue));
this.Write(";");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatValue<TValue>(resultValue)));
this.Write(";");
}
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateIntExpression(IntExpression expression, string targetVariable, bool isNullable = false)
{
string typeName = isNullable ? "int?" : "int";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(isNullable ? "null" : "0"));
this.Write(";");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.LiteralValue));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<int>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateListExpression<TElement>(ValueExpression expression, string targetVariable)
{
string typeName = GetTypeAlias<TElement>();
if (expression is null)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TElement>()));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write("> = await context.EvaluateListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateRecordExpression<TValue>(ObjectExpression<RecordDataValue> expression, string targetVariable)
{
string resultTypeName = $"Dictionary<string, {GetTypeAlias<TValue>()}?>?";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" =\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateExpressionAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateExpressionAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateStringExpression(StringExpression expression, string targetVariable, bool isNullable = false)
{
string typeName = isNullable ? "string?" : "string";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(isNullable ? "null" : "string.Empty"));
this.Write(";");
}
else if (expression.IsLiteral)
{
if (expression.LiteralValue.Contains("\n"))
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = \n \"\"\"\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.LiteralValue));
this.Write("\n \"\"\";");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.LiteralValue)));
this.Write(";");
}
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<string>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<string>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<string>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateValueExpression(ValueExpression expression, string targetVariable) =>
EvaluateValueExpression<object>(expression, targetVariable);
@@ -876,46 +191,5 @@ this.Write(").ConfigureAwait(false);");
}
}
void EvaluateMessageTemplate(TemplateLine templateLine, string variableName)
{
if (templateLine is not null)
{
this.Write("\n string ");
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
this.Write(" =\n await context.FormatTemplateAsync(\n \"\"\"");
FormatMessageTemplate(templateLine);
this.Write("\n \"\"\");");
}
else
{
this.Write("\n string? ");
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
this.Write(" = null;");
}
}
void FormatMessageTemplate(TemplateLine line)
{
foreach (string text in line.ToTemplateString().ByLine())
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(text));
}
}
}
}
@@ -1,7 +1,9 @@
<#@ template language="C#" inherits="ActionTemplate" visibility="internal" linePragmas="false" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Core" #>
<#@ include file="Snippets/Index.tt" once="true" #>
<#@ import namespace="Microsoft.Agents.ObjectModel" #>
<#@ include file="Snippets/AssignVariableTemplate.tt" once="true" #>
<#@ include file="Snippets/EvaluateValueExpressionTemplate.tt" once="true" #>
/// <summary>
/// Assigns an evaluated expression, other variable, or literal value to one or more variables.
/// </summary>
@@ -10,10 +10,7 @@
namespace Microsoft.Agents.AI.Workflows.Declarative.CodeGen
{
using Microsoft.Agents.AI.Workflows.Declarative.Extensions;
using Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
using Microsoft.Agents.ObjectModel;
using Microsoft.Extensions.AI;
using System.Collections.Generic;
using System;
/// <summary>
@@ -27,17 +24,6 @@ namespace Microsoft.Agents.AI.Workflows.Declarative.CodeGen
/// </summary>
public override string TransformText()
{
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
@@ -87,785 +73,6 @@ this.Write("\n ");
}
void EvaluateBoolExpression(BoolExpression expression, string targetVariable, bool defaultValue = false)
{
if (expression is null)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatBoolValue(defaultValue)));
this.Write(";");
}
else if (expression.IsLiteral)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatBoolValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<bool>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<bool>>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<bool>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateEnumExpression<TWrapper, TValue>(
EnumExpression<TWrapper> expression,
string targetVariable,
IDictionary<TWrapper, string> resultMap,
string defaultValue = null,
bool qualifyResult = false,
bool isNullable = false)
where TWrapper : EnumWrapper
{
string resultType = $"{GetTypeAlias<TValue>()}{(isNullable ? "?" : "")}";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatValue<TValue>(defaultValue)));
this.Write(";");
}
else if (expression.IsLiteral)
{
resultMap.TryGetValue(expression.LiteralValue, out string resultValue);
if (qualifyResult)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(".");
this.Write(this.ToStringHelper.ToStringWithCulture(resultValue));
this.Write(";");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatValue<TValue>(resultValue)));
this.Write(";");
}
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateIntExpression(IntExpression expression, string targetVariable, bool isNullable = false)
{
string typeName = isNullable ? "int?" : "int";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(isNullable ? "null" : "0"));
this.Write(";");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.LiteralValue));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<int>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateListExpression<TElement>(ValueExpression expression, string targetVariable)
{
string typeName = GetTypeAlias<TElement>();
if (expression is null)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TElement>()));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write("> = await context.EvaluateListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateRecordExpression<TValue>(ObjectExpression<RecordDataValue> expression, string targetVariable)
{
string resultTypeName = $"Dictionary<string, {GetTypeAlias<TValue>()}?>?";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" =\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateExpressionAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateExpressionAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateStringExpression(StringExpression expression, string targetVariable, bool isNullable = false)
{
string typeName = isNullable ? "string?" : "string";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(isNullable ? "null" : "string.Empty"));
this.Write(";");
}
else if (expression.IsLiteral)
{
if (expression.LiteralValue.Contains("\n"))
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = \n \"\"\"\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.LiteralValue));
this.Write("\n \"\"\";");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.LiteralValue)));
this.Write(";");
}
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<string>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<string>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<string>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateValueExpression(ValueExpression expression, string targetVariable) =>
EvaluateValueExpression<object>(expression, targetVariable);
void EvaluateValueExpression<TValue>(ValueExpression expression, string targetVariable)
{
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateMessageTemplate(TemplateLine templateLine, string variableName)
{
if (templateLine is not null)
@@ -1,7 +1,10 @@
<#@ template language="C#" inherits="ActionTemplate" visibility="internal" linePragmas="false" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Core" #>
<#@ include file="Snippets/Index.tt" once="true" #>
<#@ import namespace="Microsoft.Agents.AI.Workflows.Declarative.Extensions" #>
<#@ import namespace="Microsoft.Agents.ObjectModel" #>
<#@ include file="Snippets/AssignVariableTemplate.tt" once="true" #>
<#@ include file="Snippets/FormatMessageTemplate.tt" once="true" #>
/// <summary>
/// Assigns an evaluated message template to the "<#= this.Model.Variable #>" variable.
/// </summary>
@@ -9,11 +9,7 @@
// ------------------------------------------------------------------------------
namespace Microsoft.Agents.AI.Workflows.Declarative.CodeGen
{
using Microsoft.Agents.AI.Workflows.Declarative.Extensions;
using Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
using Microsoft.Agents.ObjectModel;
using Microsoft.Extensions.AI;
using System.Collections.Generic;
using System;
/// <summary>
@@ -27,18 +23,6 @@ namespace Microsoft.Agents.AI.Workflows.Declarative.CodeGen
/// </summary>
public override string TransformText()
{
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
this.Write("\n");
@@ -89,675 +73,6 @@ this.Write("\n ");
}
void EvaluateBoolExpression(BoolExpression expression, string targetVariable, bool defaultValue = false)
{
if (expression is null)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatBoolValue(defaultValue)));
this.Write(";");
}
else if (expression.IsLiteral)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatBoolValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<bool>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<bool>>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n bool ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<bool>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateEnumExpression<TWrapper, TValue>(
EnumExpression<TWrapper> expression,
string targetVariable,
IDictionary<TWrapper, string> resultMap,
string defaultValue = null,
bool qualifyResult = false,
bool isNullable = false)
where TWrapper : EnumWrapper
{
string resultType = $"{GetTypeAlias<TValue>()}{(isNullable ? "?" : "")}";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatValue<TValue>(defaultValue)));
this.Write(";");
}
else if (expression.IsLiteral)
{
resultMap.TryGetValue(expression.LiteralValue, out string resultValue);
if (qualifyResult)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TValue>()));
this.Write(".");
this.Write(this.ToStringHelper.ToStringWithCulture(resultValue));
this.Write(";");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatValue<TValue>(resultValue)));
this.Write(";");
}
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultType));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateIntExpression(IntExpression expression, string targetVariable, bool isNullable = false)
{
string typeName = isNullable ? "int?" : "int";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(isNullable ? "null" : "0"));
this.Write(";");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.LiteralValue));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<int>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateListExpression<TElement>(ValueExpression expression, string targetVariable)
{
string typeName = GetTypeAlias<TElement>();
if (expression is null)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(GetTypeAlias<TElement>()));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write("> = await context.EvaluateListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n IList<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateListAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateRecordExpression<TValue>(ObjectExpression<RecordDataValue> expression, string targetVariable)
{
string resultTypeName = $"Dictionary<string, {GetTypeAlias<TValue>()}?>?";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = null;");
}
else if (expression.IsLiteral)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" =\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatDataValue(expression.LiteralValue)));
this.Write(";");
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write("? ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateExpressionAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateExpressionAsync<");
this.Write(this.ToStringHelper.ToStringWithCulture(resultTypeName));
this.Write(">(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateStringExpression(StringExpression expression, string targetVariable, bool isNullable = false)
{
string typeName = isNullable ? "string?" : "string";
if (expression is null)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(isNullable ? "null" : "string.Empty"));
this.Write(";");
}
else if (expression.IsLiteral)
{
if (expression.LiteralValue.Contains("\n"))
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = \n \"\"\"\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.LiteralValue));
this.Write("\n \"\"\";");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = ");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.LiteralValue)));
this.Write(";");
}
}
else if (expression.IsVariableReference && expression.VariableReference.SegmentCount == 2)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.ReadStateAsync<string>(key: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.VariableName));
this.Write("\", scopeName: \"");
this.Write(this.ToStringHelper.ToStringWithCulture(expression.VariableReference.NamespaceAlias));
this.Write("\").ConfigureAwait(false);");
}
else if (expression.IsVariableReference)
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<string>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.VariableReference.ToString())));
this.Write(").ConfigureAwait(false);");
}
else
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(typeName));
this.Write(" ");
this.Write(this.ToStringHelper.ToStringWithCulture(targetVariable));
this.Write(" = await context.EvaluateValueAsync<string>(");
this.Write(this.ToStringHelper.ToStringWithCulture(FormatStringValue(expression.ExpressionText)));
this.Write(").ConfigureAwait(false);");
}
}
void EvaluateValueExpression(ValueExpression expression, string targetVariable) =>
EvaluateValueExpression<object>(expression, targetVariable);
@@ -867,46 +182,5 @@ this.Write(").ConfigureAwait(false);");
}
}
void EvaluateMessageTemplate(TemplateLine templateLine, string variableName)
{
if (templateLine is not null)
{
this.Write("\n string ");
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
this.Write(" =\n await context.FormatTemplateAsync(\n \"\"\"");
FormatMessageTemplate(templateLine);
this.Write("\n \"\"\");");
}
else
{
this.Write("\n string? ");
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
this.Write(" = null;");
}
}
void FormatMessageTemplate(TemplateLine line)
{
foreach (string text in line.ToTemplateString().ByLine())
{
this.Write("\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(text));
}
}
}
}
@@ -1,7 +1,9 @@
<#@ template language="C#" inherits="ActionTemplate" visibility="internal" linePragmas="false" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Core" #>
<#@ include file="Snippets/Index.tt" once="true" #>
<#@ import namespace="Microsoft.Agents.ObjectModel" #>
<#@ include file="Snippets/AssignVariableTemplate.tt" once="true" #>
<#@ include file="Snippets/EvaluateValueExpressionTemplate.tt" once="true" #>
/// <summary>
/// Assigns an evaluated expression, other variable, or literal value to the "<#= this.Model.Variable #>" variable.
/// </summary>
@@ -1,14 +0,0 @@
<#@ import namespace="Microsoft.Agents.AI.Workflows.Declarative.Extensions" #>
<#@ import namespace="Microsoft.Agents.AI.Workflows.Declarative.ObjectModel" #>
<#@ import namespace="Microsoft.Agents.ObjectModel" #>
<#@ import namespace="Microsoft.Extensions.AI" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ include file="AssignVariableTemplate.tt" once="true" #>
<#@ include file="EvaluateBoolExpressionTemplate.tt" once="true" #>
<#@ include file="EvaluateEnumExpressionTemplate.tt" once="true" #>
<#@ include file="EvaluateIntExpressionTemplate.tt" once="true" #>
<#@ include file="EvaluateListExpressionTemplate.tt" once="true" #>
<#@ include file="EvaluateRecordExpressionTemplate.tt" once="true" #>
<#@ include file="EvaluateStringExpressionTemplate.tt" once="true" #>
<#@ include file="EvaluateValueExpressionTemplate.tt" once="true" #>
<#@ include file="FormatMessageTemplate.tt" once="true" #>
@@ -17,7 +17,9 @@ internal sealed class AddConversationMessageExecutor(AddConversationMessage mode
{
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken = default)
{
Throw.IfNull(this.Model.Message);
Throw.IfNull(this.Model.ConversationId, $"{nameof(this.Model)}.{nameof(this.Model.ConversationId)}");
string conversationId = this.Evaluator.GetValue(this.Model.ConversationId).Value;
bool isWorkflowConversation = context.IsWorkflowConversation(conversationId, out string? _);
@@ -26,7 +28,7 @@ internal sealed class AddConversationMessageExecutor(AddConversationMessage mode
// Capture the created message, which includes the assigned ID.
newMessage = await agentProvider.CreateMessageAsync(conversationId, newMessage, cancellationToken).ConfigureAwait(false);
await this.AssignAsync(this.Model.Message?.Path, newMessage.ToRecord(), context).ConfigureAwait(false);
await this.AssignAsync(this.Model.Message.Path, newMessage.ToRecord(), context).ConfigureAwait(false);
if (isWorkflowConversation)
{
@@ -23,7 +23,7 @@ internal sealed class ClearAllVariablesExecutor(ClearAllVariables model, Workflo
VariablesToClear.ConversationScopedVariables => WorkflowFormulaState.DefaultScopeName,
VariablesToClear.ConversationHistory => null,
VariablesToClear.UserScopedVariables => null,
_ => null
_ => null,
};
if (scope is not null)
@@ -7,6 +7,7 @@ using Microsoft.Agents.AI.Workflows.Declarative.Interpreter;
using Microsoft.Agents.AI.Workflows.Declarative.PowerFx;
using Microsoft.Agents.ObjectModel;
using Microsoft.PowerFx.Types;
using Microsoft.Shared.Diagnostics;
namespace Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
@@ -15,8 +16,10 @@ internal sealed class CreateConversationExecutor(CreateConversation model, Workf
{
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken = default)
{
Throw.IfNull(this.Model.ConversationId, $"{nameof(this.Model)}.{nameof(this.Model.ConversationId)}");
string conversationId = await agentProvider.CreateConversationAsync(cancellationToken).ConfigureAwait(false);
await this.AssignAsync(this.Model.ConversationId?.Path, FormulaValue.New(conversationId), context).ConfigureAwait(false);
await this.AssignAsync(this.Model.ConversationId.Path, FormulaValue.New(conversationId), context).ConfigureAwait(false);
await context.QueueConversationUpdateAsync(conversationId, cancellationToken).ConfigureAwait(false);
return default;
@@ -18,12 +18,12 @@ internal sealed class EditTableV2Executor(EditTableV2 model, WorkflowFormulaStat
{
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken = default)
{
PropertyPath variablePath = Throw.IfNull(this.Model.ItemsVariable?.Path, $"{nameof(this.Model)}.{nameof(this.Model.ItemsVariable)}");
Throw.IfNull(this.Model.ItemsVariable, $"{nameof(this.Model)}.{nameof(this.Model.ItemsVariable)}");
FormulaValue table = context.ReadState(variablePath);
FormulaValue table = context.ReadState(this.Model.ItemsVariable);
if (table is not TableValue tableValue)
{
throw this.Exception($"Require '{variablePath}' to be a table, not: '{table.GetType().Name}'.");
throw this.Exception($"Require '{this.Model.ItemsVariable.Path}' to be a table, not: '{table.GetType().Name}'.");
}
EditTableOperation? changeType = this.Model.ChangeType;
@@ -33,12 +33,12 @@ internal sealed class EditTableV2Executor(EditTableV2 model, WorkflowFormulaStat
EvaluationResult<DataValue> expressionResult = this.Evaluator.GetValue(addItemValue);
RecordValue newRecord = BuildRecord(tableValue.Type.ToRecord(), expressionResult.Value.ToFormula());
await tableValue.AppendAsync(newRecord, cancellationToken).ConfigureAwait(false);
await this.AssignAsync(variablePath, newRecord, context).ConfigureAwait(false);
await this.AssignAsync(this.Model.ItemsVariable, newRecord, context).ConfigureAwait(false);
}
else if (changeType is ClearItemsOperation)
{
await tableValue.ClearAsync(cancellationToken).ConfigureAwait(false);
await this.AssignAsync(variablePath, FormulaValue.NewBlank(), context).ConfigureAwait(false);
await this.AssignAsync(this.Model.ItemsVariable, FormulaValue.NewBlank(), context).ConfigureAwait(false);
}
else if (changeType is RemoveItemOperation removeItemOperation)
{
@@ -46,8 +46,8 @@ internal sealed class EditTableV2Executor(EditTableV2 model, WorkflowFormulaStat
EvaluationResult<DataValue> expressionResult = this.Evaluator.GetValue(removeItemValue);
if (expressionResult.Value.ToFormula() is TableValue removeItemTable)
{
await tableValue.RemoveAsync(removeItemTable?.Rows.Select(row => row.Value), all: true, cancellationToken).ConfigureAwait(false);
await this.AssignAsync(variablePath, FormulaValue.NewBlank(), context).ConfigureAwait(false);
await tableValue.RemoveAsync(removeItemTable.Rows.Select(row => row.Value), all: true, cancellationToken).ConfigureAwait(false);
await this.AssignAsync(this.Model.ItemsVariable, FormulaValue.NewBlank(), context).ConfigureAwait(false);
}
}
else if (changeType is TakeLastItemOperation)
@@ -56,7 +56,7 @@ internal sealed class EditTableV2Executor(EditTableV2 model, WorkflowFormulaStat
if (lastRow is not null)
{
await tableValue.RemoveAsync([lastRow], all: true, cancellationToken).ConfigureAwait(false);
await this.AssignAsync(variablePath, lastRow, context).ConfigureAwait(false);
await this.AssignAsync(this.Model.ItemsVariable, lastRow, context).ConfigureAwait(false);
}
}
else if (changeType is TakeFirstItemOperation)
@@ -65,7 +65,7 @@ internal sealed class EditTableV2Executor(EditTableV2 model, WorkflowFormulaStat
if (firstRow is not null)
{
await tableValue.RemoveAsync([firstRow], all: true, cancellationToken).ConfigureAwait(false);
await this.AssignAsync(variablePath, firstRow, context).ConfigureAwait(false);
await this.AssignAsync(this.Model.ItemsVariable, firstRow, context).ConfigureAwait(false);
}
}
@@ -19,24 +19,18 @@ internal sealed class ParseValueExecutor(ParseValue model, WorkflowFormulaState
{
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken = default)
{
PropertyPath variablePath = Throw.IfNull(this.Model.Variable?.Path, $"{nameof(this.Model)}.{nameof(model.Variable)}");
Throw.IfNull(this.Model.ValueType, $"{nameof(this.Model)}.{nameof(model.ValueType)}");
Throw.IfNull(this.Model.Variable, $"{nameof(this.Model)}.{nameof(model.Variable)}");
ValueExpression valueExpression = Throw.IfNull(this.Model.Value, $"{nameof(this.Model)}.{nameof(this.Model.Value)}");
EvaluationResult<DataValue> expressionResult = this.Evaluator.GetValue(valueExpression);
FormulaValue parsedValue;
if (this.Model.ValueType is not null)
{
VariableType targetType = new(this.Model.ValueType);
object? parsedResult = expressionResult.Value.ToObject().ConvertType(targetType);
parsedValue = parsedResult.ToFormula();
}
else
{
parsedValue = expressionResult.Value.ToFormula();
}
VariableType targetType = new(this.Model.ValueType);
object? parsedResult = expressionResult.Value.ToObject().ConvertType(targetType);
parsedValue = parsedResult.ToFormula();
await this.AssignAsync(variablePath, parsedValue, context).ConfigureAwait(false);
await this.AssignAsync(this.Model.Variable.Path, parsedValue, context).ConfigureAwait(false);
return default;
}
@@ -17,6 +17,7 @@ internal sealed class ResetVariableExecutor(ResetVariable model, WorkflowFormula
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken = default)
{
Throw.IfNull(this.Model.Variable, $"{nameof(this.Model)}.{nameof(model.Variable)}");
await context.QueueStateResetAsync(this.Model.Variable, cancellationToken).ConfigureAwait(false);
Debug.WriteLine(
$"""
@@ -16,13 +16,15 @@ internal sealed class RetrieveConversationMessageExecutor(RetrieveConversationMe
{
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken = default)
{
Throw.IfNull(this.Model.Message);
Throw.IfNull(this.Model.ConversationId, $"{nameof(this.Model)}.{nameof(this.Model.ConversationId)}");
string conversationId = this.Evaluator.GetValue(this.Model.ConversationId).Value;
string messageId = this.Evaluator.GetValue(Throw.IfNull(this.Model.MessageId, $"{nameof(this.Model)}.{nameof(this.Model.MessageId)}")).Value;
ChatMessage message = await agentProvider.GetMessageAsync(conversationId, messageId, cancellationToken).ConfigureAwait(false);
await this.AssignAsync(this.Model.Message?.Path, message.ToRecord(), context).ConfigureAwait(false);
await this.AssignAsync(this.Model.Message.Path, message.ToRecord(), context).ConfigureAwait(false);
return default;
}
@@ -18,11 +18,13 @@ internal sealed class RetrieveConversationMessagesExecutor(RetrieveConversationM
{
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken = default)
{
Throw.IfNull(this.Model.Messages);
Throw.IfNull(this.Model.ConversationId, $"{nameof(this.Model)}.{nameof(this.Model.ConversationId)}");
string conversationId = this.Evaluator.GetValue(this.Model.ConversationId).Value;
List<ChatMessage> messages = [];
await foreach (var m in agentProvider.GetMessagesAsync(
await foreach (ChatMessage message in agentProvider.GetMessagesAsync(
conversationId,
limit: this.GetLimit(),
after: this.GetMessage(this.Model.MessageAfter),
@@ -30,21 +32,16 @@ internal sealed class RetrieveConversationMessagesExecutor(RetrieveConversationM
newestFirst: this.IsDescending(),
cancellationToken).ConfigureAwait(false))
{
messages.Add(m);
messages.Add(message);
}
await this.AssignAsync(this.Model.Messages?.Path, messages.ToTable(), context).ConfigureAwait(false);
await this.AssignAsync(this.Model.Messages.Path, messages.ToTable(), context).ConfigureAwait(false);
return default;
}
private int? GetLimit()
{
if (this.Model.Limit is null)
{
return null;
}
long limit = this.Evaluator.GetValue(this.Model.Limit).Value;
return Convert.ToInt32(Math.Min(limit, 100));
}
@@ -61,11 +58,6 @@ internal sealed class RetrieveConversationMessagesExecutor(RetrieveConversationM
private bool IsDescending()
{
if (this.Model.SortOrder is null)
{
return false;
}
AgentMessageSortOrderWrapper sortOrderWrapper = this.Evaluator.GetValue(this.Model.SortOrder).Value;
return sortOrderWrapper.Value == AgentMessageSortOrder.NewestFirst;
@@ -7,6 +7,7 @@ using Microsoft.Agents.AI.Workflows.Declarative.Interpreter;
using Microsoft.Agents.AI.Workflows.Declarative.PowerFx;
using Microsoft.Agents.ObjectModel;
using Microsoft.PowerFx.Types;
using Microsoft.Shared.Diagnostics;
namespace Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
@@ -15,16 +16,12 @@ internal sealed class SetTextVariableExecutor(SetTextVariable model, WorkflowFor
{
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken = default)
{
if (this.Model.Value is null)
{
await this.AssignAsync(this.Model.Variable?.Path, FormulaValue.NewBlank(), context).ConfigureAwait(false);
}
else
{
FormulaValue expressionResult = FormulaValue.New(this.Engine.Format(this.Model.Value));
Throw.IfNull(this.Model.Variable);
Throw.IfNull(this.Model.Value);
await this.AssignAsync(this.Model.Variable?.Path, expressionResult, context).ConfigureAwait(false);
}
FormulaValue expressionResult = FormulaValue.New(this.Engine.Format(this.Model.Value));
await this.AssignAsync(this.Model.Variable.Path, expressionResult, context).ConfigureAwait(false);
return default;
}
@@ -7,7 +7,7 @@ using Microsoft.Agents.AI.Workflows.Declarative.Interpreter;
using Microsoft.Agents.AI.Workflows.Declarative.PowerFx;
using Microsoft.Agents.ObjectModel;
using Microsoft.Agents.ObjectModel.Abstractions;
using Microsoft.PowerFx.Types;
using Microsoft.Shared.Diagnostics;
namespace Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
@@ -16,16 +16,12 @@ internal sealed class SetVariableExecutor(SetVariable model, WorkflowFormulaStat
{
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken = default)
{
if (this.Model.Value is null)
{
await this.AssignAsync(this.Model.Variable?.Path, FormulaValue.NewBlank(), context).ConfigureAwait(false);
}
else
{
EvaluationResult<DataValue> expressionResult = this.Evaluator.GetValue(this.Model.Value);
Throw.IfNull(this.Model.Variable);
Throw.IfNull(this.Model.Value);
await this.AssignAsync(this.Model.Variable?.Path, expressionResult.Value.ToFormula(), context).ConfigureAwait(false);
}
EvaluationResult<DataValue> expressionResult = this.Evaluator.GetValue(this.Model.Value);
await this.AssignAsync(this.Model.Variable.Path, expressionResult.Value.ToFormula(), context).ConfigureAwait(false);
return default;
}
@@ -189,7 +189,7 @@ public sealed class ChatHistoryMemoryProvider : AIContextProvider, IDisposable
{
// Get the text from the current request messages
var requestText = string.Join("\n", context.RequestMessages
.Where(m => m.GetAgentRequestMessageSource() == AgentRequestMessageSourceType.External)
.Where(m => m.GetAgentRequestMessageSourceType() == AgentRequestMessageSourceType.External)
.Where(m => m != null && !string.IsNullOrWhiteSpace(m.Text))
.Select(m => m.Text));
@@ -245,7 +245,7 @@ public sealed class ChatHistoryMemoryProvider : AIContextProvider, IDisposable
var collection = await this.EnsureCollectionExistsAsync(cancellationToken).ConfigureAwait(false);
List<Dictionary<string, object?>> itemsToStore = context.RequestMessages
.Where(m => m.GetAgentRequestMessageSource() == AgentRequestMessageSourceType.External)
.Where(m => m.GetAgentRequestMessageSourceType() == AgentRequestMessageSourceType.External)
.Concat(context.ResponseMessages ?? [])
.Select(message => new Dictionary<string, object?>
{
@@ -118,7 +118,7 @@ public sealed class TextSearchProvider : AIContextProvider
// Aggregate text from memory + current request messages.
var sbInput = new StringBuilder();
var requestMessagesText = context.RequestMessages
.Where(m => m.GetAgentRequestMessageSource() == AgentRequestMessageSourceType.External)
.Where(m => m.GetAgentRequestMessageSourceType() == AgentRequestMessageSourceType.External)
.Where(x => !string.IsNullOrWhiteSpace(x?.Text)).Select(x => x.Text);
foreach (var messageText in this._recentMessagesText.Concat(requestMessagesText))
{
@@ -182,7 +182,7 @@ public sealed class TextSearchProvider : AIContextProvider
}
var messagesText = context.RequestMessages
.Where(m => m.GetAgentRequestMessageSource() == AgentRequestMessageSourceType.External)
.Where(m => m.GetAgentRequestMessageSourceType() == AgentRequestMessageSourceType.External)
.Concat(context.ResponseMessages ?? [])
.Where(m =>
this._recentMessageRolesIncluded.Contains(m.Role) &&
@@ -19,7 +19,7 @@ public class AIContextProviderTests
#region InvokingAsync Message Stamping Tests
[Fact]
public async Task InvokingAsync_StampsMessagesWithSourceTypeAndSourceAsync()
public async Task InvokingAsync_StampsMessagesWithSourceTypeAndSourceIdAsync()
{
// Arrange
var provider = new TestAIContextProviderWithMessages();
@@ -32,18 +32,18 @@ public class AIContextProviderTests
Assert.NotNull(aiContext.Messages);
ChatMessage message = aiContext.Messages.Single();
Assert.NotNull(message.AdditionalProperties);
Assert.True(message.AdditionalProperties.TryGetValue(AgentRequestMessageSourceType.AdditionalPropertiesKey, out object? sourceType));
Assert.Equal(AgentRequestMessageSourceType.AIContextProvider, sourceType);
Assert.True(message.AdditionalProperties.TryGetValue(AgentRequestMessageSource.AdditionalPropertiesKey, out object? source));
Assert.Equal(typeof(TestAIContextProviderWithMessages).FullName, source);
Assert.True(message.AdditionalProperties.TryGetValue(AgentRequestMessageSourceAttribution.AdditionalPropertiesKey, out object? attribution));
var typedAttribution = Assert.IsType<AgentRequestMessageSourceAttribution>(attribution);
Assert.Equal(AgentRequestMessageSourceType.AIContextProvider, typedAttribution.SourceType);
Assert.Equal(typeof(TestAIContextProviderWithMessages).FullName, typedAttribution.SourceId);
}
[Fact]
public async Task InvokingAsync_WithCustomSourceName_StampsMessagesWithCustomSourceAsync()
public async Task InvokingAsync_WithCustomSourceId_StampsMessagesWithCustomSourceIdAsync()
{
// Arrange
const string CustomSourceName = "CustomContextSource";
var provider = new TestAIContextProviderWithCustomSource(CustomSourceName);
const string CustomSourceId = "CustomContextSource";
var provider = new TestAIContextProviderWithCustomSource(CustomSourceId);
var context = new AIContextProvider.InvokingContext(s_mockAgent, s_mockSession, [new ChatMessage(ChatRole.User, "Request")]);
// Act
@@ -53,10 +53,10 @@ public class AIContextProviderTests
Assert.NotNull(aiContext.Messages);
ChatMessage message = aiContext.Messages.Single();
Assert.NotNull(message.AdditionalProperties);
Assert.True(message.AdditionalProperties.TryGetValue(AgentRequestMessageSourceType.AdditionalPropertiesKey, out object? sourceType));
Assert.Equal(AgentRequestMessageSourceType.AIContextProvider, sourceType);
Assert.True(message.AdditionalProperties.TryGetValue(AgentRequestMessageSource.AdditionalPropertiesKey, out object? source));
Assert.Equal(CustomSourceName, source);
Assert.True(message.AdditionalProperties.TryGetValue(AgentRequestMessageSourceAttribution.AdditionalPropertiesKey, out object? attribution));
var typedAttribution = Assert.IsType<AgentRequestMessageSourceAttribution>(attribution);
Assert.Equal(AgentRequestMessageSourceType.AIContextProvider, typedAttribution.SourceType);
Assert.Equal(CustomSourceId, typedAttribution.SourceId);
}
[Fact]
@@ -73,10 +73,10 @@ public class AIContextProviderTests
Assert.NotNull(aiContext.Messages);
ChatMessage message = aiContext.Messages.Single();
Assert.NotNull(message.AdditionalProperties);
Assert.True(message.AdditionalProperties.TryGetValue(AgentRequestMessageSourceType.AdditionalPropertiesKey, out object? sourceType));
Assert.Equal(AgentRequestMessageSourceType.AIContextProvider, sourceType);
Assert.True(message.AdditionalProperties.TryGetValue(AgentRequestMessageSource.AdditionalPropertiesKey, out object? source));
Assert.Equal(typeof(TestAIContextProviderWithPreStampedMessages).FullName, source);
Assert.True(message.AdditionalProperties.TryGetValue(AgentRequestMessageSourceAttribution.AdditionalPropertiesKey, out object? attribution));
var typedAttribution = Assert.IsType<AgentRequestMessageSourceAttribution>(attribution);
Assert.Equal(AgentRequestMessageSourceType.AIContextProvider, typedAttribution.SourceType);
Assert.Equal(typeof(TestAIContextProviderWithPreStampedMessages).FullName, typedAttribution.SourceId);
}
[Fact]
@@ -97,10 +97,10 @@ public class AIContextProviderTests
foreach (ChatMessage message in messageList)
{
Assert.NotNull(message.AdditionalProperties);
Assert.True(message.AdditionalProperties.TryGetValue(AgentRequestMessageSourceType.AdditionalPropertiesKey, out object? sourceType));
Assert.Equal(AgentRequestMessageSourceType.AIContextProvider, sourceType);
Assert.True(message.AdditionalProperties.TryGetValue(AgentRequestMessageSource.AdditionalPropertiesKey, out object? source));
Assert.Equal(typeof(TestAIContextProviderWithMultipleMessages).FullName, source);
Assert.True(message.AdditionalProperties.TryGetValue(AgentRequestMessageSourceAttribution.AdditionalPropertiesKey, out object? attribution));
var typedAttribution = Assert.IsType<AgentRequestMessageSourceAttribution>(attribution);
Assert.Equal(AgentRequestMessageSourceType.AIContextProvider, typedAttribution.SourceType);
Assert.Equal(typeof(TestAIContextProviderWithMultipleMessages).FullName, typedAttribution.SourceId);
}
}
@@ -486,7 +486,7 @@ public class AIContextProviderTests
private sealed class TestAIContextProviderWithCustomSource : AIContextProvider
{
public TestAIContextProviderWithCustomSource(string sourceName) : base(sourceName)
public TestAIContextProviderWithCustomSource(string sourceId) : base(sourceId)
{
}
@@ -504,8 +504,7 @@ public class AIContextProviderTests
var message = new ChatMessage(ChatRole.System, "Pre-stamped Message");
message.AdditionalProperties = new AdditionalPropertiesDictionary
{
[AgentRequestMessageSourceType.AdditionalPropertiesKey] = AgentRequestMessageSourceType.AIContextProvider,
[AgentRequestMessageSource.AdditionalPropertiesKey] = this.GetType().FullName!
[AgentRequestMessageSourceAttribution.AdditionalPropertiesKey] = new AgentRequestMessageSourceAttribution(AgentRequestMessageSourceType.AIContextProvider, this.GetType().FullName!)
};
return new(new AIContext
{
@@ -0,0 +1,466 @@
// Copyright (c) Microsoft. All rights reserved.
namespace Microsoft.Agents.AI.Abstractions.UnitTests;
/// <summary>
/// Contains tests for the <see cref="AgentRequestMessageSourceAttribution"/> struct.
/// </summary>
public sealed class AgentRequestMessageSourceAttributionTests
{
#region Constructor Tests
[Fact]
public void Constructor_SetsSourceTypeAndSourceId()
{
// Arrange
AgentRequestMessageSourceType expectedType = AgentRequestMessageSourceType.AIContextProvider;
const string ExpectedId = "MyProvider";
// Act
AgentRequestMessageSourceAttribution attribution = new(expectedType, ExpectedId);
// Assert
Assert.Equal(expectedType, attribution.SourceType);
Assert.Equal(ExpectedId, attribution.SourceId);
}
[Fact]
public void Constructor_WithNullSourceId_SetsNullSourceId()
{
// Arrange
AgentRequestMessageSourceType sourceType = AgentRequestMessageSourceType.ChatHistory;
// Act
AgentRequestMessageSourceAttribution attribution = new(sourceType, null);
// Assert
Assert.Equal(sourceType, attribution.SourceType);
Assert.Null(attribution.SourceId);
}
#endregion
#region AdditionalPropertiesKey Tests
[Fact]
public void AdditionalPropertiesKey_IsAttribution()
{
// Assert
Assert.Equal("_attribution", AgentRequestMessageSourceAttribution.AdditionalPropertiesKey);
}
#endregion
#region Default Value Tests
[Fact]
public void Default_HasDefaultSourceTypeAndNullSourceId()
{
// Arrange & Act
AgentRequestMessageSourceAttribution attribution = default;
// Assert
Assert.Equal(default, attribution.SourceType);
Assert.Null(attribution.SourceId);
}
#endregion
#region Equals (IEquatable) Tests
[Fact]
public void Equals_WithSameSourceTypeAndSourceId_ReturnsTrue()
{
// Arrange
AgentRequestMessageSourceAttribution attribution1 = new(AgentRequestMessageSourceType.AIContextProvider, "Provider1");
AgentRequestMessageSourceAttribution attribution2 = new(AgentRequestMessageSourceType.AIContextProvider, "Provider1");
// Act
bool result = attribution1.Equals(attribution2);
// Assert
Assert.True(result);
}
[Fact]
public void Equals_WithDifferentSourceType_ReturnsFalse()
{
// Arrange
AgentRequestMessageSourceAttribution attribution1 = new(AgentRequestMessageSourceType.AIContextProvider, "Provider1");
AgentRequestMessageSourceAttribution attribution2 = new(AgentRequestMessageSourceType.ChatHistory, "Provider1");
// Act
bool result = attribution1.Equals(attribution2);
// Assert
Assert.False(result);
}
[Fact]
public void Equals_WithDifferentSourceId_ReturnsFalse()
{
// Arrange
AgentRequestMessageSourceAttribution attribution1 = new(AgentRequestMessageSourceType.AIContextProvider, "Provider1");
AgentRequestMessageSourceAttribution attribution2 = new(AgentRequestMessageSourceType.AIContextProvider, "Provider2");
// Act
bool result = attribution1.Equals(attribution2);
// Assert
Assert.False(result);
}
[Fact]
public void Equals_WithDifferentSourceTypeAndSourceId_ReturnsFalse()
{
// Arrange
AgentRequestMessageSourceAttribution attribution1 = new(AgentRequestMessageSourceType.AIContextProvider, "Provider1");
AgentRequestMessageSourceAttribution attribution2 = new(AgentRequestMessageSourceType.ChatHistory, "Provider2");
// Act
bool result = attribution1.Equals(attribution2);
// Assert
Assert.False(result);
}
[Fact]
public void Equals_WithDifferentCaseSourceId_ReturnsFalse()
{
// Arrange
AgentRequestMessageSourceAttribution attribution1 = new(AgentRequestMessageSourceType.AIContextProvider, "Provider");
AgentRequestMessageSourceAttribution attribution2 = new(AgentRequestMessageSourceType.AIContextProvider, "provider");
// Act
bool result = attribution1.Equals(attribution2);
// Assert
Assert.False(result);
}
[Fact]
public void Equals_BothDefaultValues_ReturnsTrue()
{
// Arrange
AgentRequestMessageSourceAttribution attribution1 = default;
AgentRequestMessageSourceAttribution attribution2 = default;
// Act
bool result = attribution1.Equals(attribution2);
// Assert
Assert.True(result);
}
[Fact]
public void Equals_WithBothNullSourceIds_ReturnsTrue()
{
// Arrange
AgentRequestMessageSourceAttribution attribution1 = new(AgentRequestMessageSourceType.External, null!);
AgentRequestMessageSourceAttribution attribution2 = new(AgentRequestMessageSourceType.External, null!);
// Act
bool result = attribution1.Equals(attribution2);
// Assert
Assert.True(result);
}
[Fact]
public void Equals_WithOneNullSourceId_ReturnsFalse()
{
// Arrange
AgentRequestMessageSourceAttribution attribution1 = new(AgentRequestMessageSourceType.External, "Provider1");
AgentRequestMessageSourceAttribution attribution2 = new(AgentRequestMessageSourceType.External, null!);
// Act
bool result = attribution1.Equals(attribution2);
// Assert
Assert.False(result);
}
#endregion
#region Object.Equals Tests
[Fact]
public void ObjectEquals_WithEqualAttribution_ReturnsTrue()
{
// Arrange
AgentRequestMessageSourceAttribution attribution1 = new(AgentRequestMessageSourceType.ChatHistory, "Provider");
object attribution2 = new AgentRequestMessageSourceAttribution(AgentRequestMessageSourceType.ChatHistory, "Provider");
// Act
bool result = attribution1.Equals(attribution2);
// Assert
Assert.True(result);
}
[Fact]
public void ObjectEquals_WithDifferentType_ReturnsFalse()
{
// Arrange
AgentRequestMessageSourceAttribution attribution = new(AgentRequestMessageSourceType.ChatHistory, "Provider");
object other = "NotAnAttribution";
// Act
bool result = attribution.Equals(other);
// Assert
Assert.False(result);
}
[Fact]
public void ObjectEquals_WithNullObject_ReturnsFalse()
{
// Arrange
AgentRequestMessageSourceAttribution attribution = new(AgentRequestMessageSourceType.ChatHistory, "Provider");
object? other = null;
// Act
bool result = attribution.Equals(other);
// Assert
Assert.False(result);
}
[Fact]
public void ObjectEquals_WithBoxedDifferentAttribution_ReturnsFalse()
{
// Arrange
AgentRequestMessageSourceAttribution attribution1 = new(AgentRequestMessageSourceType.ChatHistory, "Provider1");
object attribution2 = new AgentRequestMessageSourceAttribution(AgentRequestMessageSourceType.ChatHistory, "Provider2");
// Act
bool result = attribution1.Equals(attribution2);
// Assert
Assert.False(result);
}
#endregion
#region GetHashCode Tests
[Fact]
public void GetHashCode_WithSameValues_ReturnsSameHashCode()
{
// Arrange
AgentRequestMessageSourceAttribution attribution1 = new(AgentRequestMessageSourceType.AIContextProvider, "Provider");
AgentRequestMessageSourceAttribution attribution2 = new(AgentRequestMessageSourceType.AIContextProvider, "Provider");
// Act
int hashCode1 = attribution1.GetHashCode();
int hashCode2 = attribution2.GetHashCode();
// Assert
Assert.Equal(hashCode1, hashCode2);
}
[Fact]
public void GetHashCode_WithDifferentSourceType_ReturnsDifferentHashCode()
{
// Arrange
AgentRequestMessageSourceAttribution attribution1 = new(AgentRequestMessageSourceType.AIContextProvider, "Provider");
AgentRequestMessageSourceAttribution attribution2 = new(AgentRequestMessageSourceType.ChatHistory, "Provider");
// Act
int hashCode1 = attribution1.GetHashCode();
int hashCode2 = attribution2.GetHashCode();
// Assert
Assert.NotEqual(hashCode1, hashCode2);
}
[Fact]
public void GetHashCode_WithDifferentSourceId_ReturnsDifferentHashCode()
{
// Arrange
AgentRequestMessageSourceAttribution attribution1 = new(AgentRequestMessageSourceType.AIContextProvider, "Provider1");
AgentRequestMessageSourceAttribution attribution2 = new(AgentRequestMessageSourceType.AIContextProvider, "Provider2");
// Act
int hashCode1 = attribution1.GetHashCode();
int hashCode2 = attribution2.GetHashCode();
// Assert
Assert.NotEqual(hashCode1, hashCode2);
}
[Fact]
public void GetHashCode_ConsistentWithEquals()
{
// Arrange
AgentRequestMessageSourceAttribution attribution1 = new(AgentRequestMessageSourceType.External, "Provider");
AgentRequestMessageSourceAttribution attribution2 = new(AgentRequestMessageSourceType.External, "Provider");
// Act & Assert
Assert.True(attribution1.Equals(attribution2));
Assert.Equal(attribution1.GetHashCode(), attribution2.GetHashCode());
}
[Fact]
public void GetHashCode_WithNullSourceId_DoesNotThrow()
{
// Arrange
AgentRequestMessageSourceAttribution attribution = new(AgentRequestMessageSourceType.External, null!);
// Act
int hashCode = attribution.GetHashCode();
// Assert
Assert.IsType<int>(hashCode);
}
#endregion
#region Equality Operator Tests
[Fact]
public void EqualityOperator_WithEqualValues_ReturnsTrue()
{
// Arrange
AgentRequestMessageSourceAttribution attribution1 = new(AgentRequestMessageSourceType.AIContextProvider, "Provider");
AgentRequestMessageSourceAttribution attribution2 = new(AgentRequestMessageSourceType.AIContextProvider, "Provider");
// Act
bool result = attribution1 == attribution2;
// Assert
Assert.True(result);
}
[Fact]
public void EqualityOperator_WithDifferentValues_ReturnsFalse()
{
// Arrange
AgentRequestMessageSourceAttribution attribution1 = new(AgentRequestMessageSourceType.AIContextProvider, "Provider1");
AgentRequestMessageSourceAttribution attribution2 = new(AgentRequestMessageSourceType.ChatHistory, "Provider2");
// Act
bool result = attribution1 == attribution2;
// Assert
Assert.False(result);
}
[Fact]
public void EqualityOperator_WithBothDefault_ReturnsTrue()
{
// Arrange
AgentRequestMessageSourceAttribution attribution1 = default;
AgentRequestMessageSourceAttribution attribution2 = default;
// Act
bool result = attribution1 == attribution2;
// Assert
Assert.True(result);
}
[Fact]
public void EqualityOperator_WithDifferentSourceTypeOnly_ReturnsFalse()
{
// Arrange
AgentRequestMessageSourceAttribution attribution1 = new(AgentRequestMessageSourceType.AIContextProvider, "Provider");
AgentRequestMessageSourceAttribution attribution2 = new(AgentRequestMessageSourceType.External, "Provider");
// Act
bool result = attribution1 == attribution2;
// Assert
Assert.False(result);
}
[Fact]
public void EqualityOperator_WithDifferentSourceIdOnly_ReturnsFalse()
{
// Arrange
AgentRequestMessageSourceAttribution attribution1 = new(AgentRequestMessageSourceType.AIContextProvider, "Provider1");
AgentRequestMessageSourceAttribution attribution2 = new(AgentRequestMessageSourceType.AIContextProvider, "Provider2");
// Act
bool result = attribution1 == attribution2;
// Assert
Assert.False(result);
}
#endregion
#region Inequality Operator Tests
[Fact]
public void InequalityOperator_WithEqualValues_ReturnsFalse()
{
// Arrange
AgentRequestMessageSourceAttribution attribution1 = new(AgentRequestMessageSourceType.AIContextProvider, "Provider");
AgentRequestMessageSourceAttribution attribution2 = new(AgentRequestMessageSourceType.AIContextProvider, "Provider");
// Act
bool result = attribution1 != attribution2;
// Assert
Assert.False(result);
}
[Fact]
public void InequalityOperator_WithDifferentValues_ReturnsTrue()
{
// Arrange
AgentRequestMessageSourceAttribution attribution1 = new(AgentRequestMessageSourceType.AIContextProvider, "Provider1");
AgentRequestMessageSourceAttribution attribution2 = new(AgentRequestMessageSourceType.ChatHistory, "Provider2");
// Act
bool result = attribution1 != attribution2;
// Assert
Assert.True(result);
}
[Fact]
public void InequalityOperator_WithBothDefault_ReturnsFalse()
{
// Arrange
AgentRequestMessageSourceAttribution attribution1 = default;
AgentRequestMessageSourceAttribution attribution2 = default;
// Act
bool result = attribution1 != attribution2;
// Assert
Assert.False(result);
}
[Fact]
public void InequalityOperator_WithDifferentSourceTypeOnly_ReturnsTrue()
{
// Arrange
AgentRequestMessageSourceAttribution attribution1 = new(AgentRequestMessageSourceType.AIContextProvider, "Provider");
AgentRequestMessageSourceAttribution attribution2 = new(AgentRequestMessageSourceType.External, "Provider");
// Act
bool result = attribution1 != attribution2;
// Assert
Assert.True(result);
}
[Fact]
public void InequalityOperator_WithDifferentSourceIdOnly_ReturnsTrue()
{
// Arrange
AgentRequestMessageSourceAttribution attribution1 = new(AgentRequestMessageSourceType.AIContextProvider, "Provider1");
AgentRequestMessageSourceAttribution attribution2 = new(AgentRequestMessageSourceType.AIContextProvider, "Provider2");
// Act
bool result = attribution1 != attribution2;
// Assert
Assert.True(result);
}
#endregion
}
@@ -5,7 +5,7 @@ using System;
namespace Microsoft.Agents.AI.Abstractions.UnitTests;
/// <summary>
/// Contains tests for the <see cref="AgentRequestMessageSourceType"/> class.
/// Contains tests for the <see cref="AgentRequestMessageSourceType"/> struct.
/// </summary>
public sealed class AgentRequestMessageSourceTypeTests
{
@@ -38,6 +38,16 @@ public sealed class AgentRequestMessageSourceTypeTests
Assert.Throws<ArgumentException>(() => new AgentRequestMessageSourceType(string.Empty));
}
[Fact]
public void Default_DefaultsToExternal()
{
// Act
AgentRequestMessageSourceType defaultSource = default;
// Assert
Assert.Equal(AgentRequestMessageSourceType.External, defaultSource);
}
#endregion
#region Static Properties Tests
@@ -49,7 +59,6 @@ public sealed class AgentRequestMessageSourceTypeTests
AgentRequestMessageSourceType source = AgentRequestMessageSourceType.External;
// Assert
Assert.NotNull(source);
Assert.Equal("External", source.Value);
}
@@ -60,7 +69,6 @@ public sealed class AgentRequestMessageSourceTypeTests
AgentRequestMessageSourceType source = AgentRequestMessageSourceType.AIContextProvider;
// Assert
Assert.NotNull(source);
Assert.Equal("AIContextProvider", source.Value);
}
@@ -71,22 +79,11 @@ public sealed class AgentRequestMessageSourceTypeTests
AgentRequestMessageSourceType source = AgentRequestMessageSourceType.ChatHistory;
// Assert
Assert.NotNull(source);
Assert.Equal("ChatHistory", source.Value);
}
[Fact]
public void AdditionalPropertiesKey_ReturnsExpectedValue()
{
// Arrange & Act
string key = AgentRequestMessageSourceType.AdditionalPropertiesKey;
// Assert
Assert.Equal("Agent.RequestMessageSourceType", key);
}
[Fact]
public void StaticProperties_ReturnSameInstanceOnMultipleCalls()
public void StaticProperties_ReturnEqualValuesOnMultipleCalls()
{
// Arrange & Act
AgentRequestMessageSourceType external1 = AgentRequestMessageSourceType.External;
@@ -97,9 +94,9 @@ public sealed class AgentRequestMessageSourceTypeTests
AgentRequestMessageSourceType chatHistory2 = AgentRequestMessageSourceType.ChatHistory;
// Assert
Assert.Same(external1, external2);
Assert.Same(aiContextProvider1, aiContextProvider2);
Assert.Same(chatHistory1, chatHistory2);
Assert.Equal(external1, external2);
Assert.Equal(aiContextProvider1, aiContextProvider2);
Assert.Equal(chatHistory1, chatHistory2);
}
#endregion
@@ -148,7 +145,7 @@ public sealed class AgentRequestMessageSourceTypeTests
}
[Fact]
public void Equals_WithNull_ReturnsFalse()
public void Equals_WithNullObject_ReturnsFalse()
{
// Arrange
AgentRequestMessageSourceType source = new("Test");
@@ -314,11 +311,11 @@ public sealed class AgentRequestMessageSourceTypeTests
}
[Fact]
public void EqualityOperator_WithBothNull_ReturnsTrue()
public void EqualityOperator_WithDefaultValues_ReturnsTrue()
{
// Arrange
AgentRequestMessageSourceType? source1 = null;
AgentRequestMessageSourceType? source2 = null;
AgentRequestMessageSourceType source1 = default;
AgentRequestMessageSourceType source2 = default;
// Act
bool result = source1 == source2;
@@ -327,34 +324,6 @@ public sealed class AgentRequestMessageSourceTypeTests
Assert.True(result);
}
[Fact]
public void EqualityOperator_WithLeftNull_ReturnsFalse()
{
// Arrange
AgentRequestMessageSourceType? source1 = null;
AgentRequestMessageSourceType source2 = new("Test");
// Act
bool result = source1 == source2;
// Assert
Assert.False(result);
}
[Fact]
public void EqualityOperator_WithRightNull_ReturnsFalse()
{
// Arrange
AgentRequestMessageSourceType source1 = new("Test");
AgentRequestMessageSourceType? source2 = null;
// Act
bool result = source1 == source2;
// Assert
Assert.False(result);
}
[Fact]
public void EqualityOperator_WithStaticInstances_ReturnsTrue()
{
@@ -416,11 +385,11 @@ public sealed class AgentRequestMessageSourceTypeTests
}
[Fact]
public void InequalityOperator_WithBothNull_ReturnsFalse()
public void InequalityOperator_WithBothDefault_ReturnsFalse()
{
// Arrange
AgentRequestMessageSourceType? source1 = null;
AgentRequestMessageSourceType? source2 = null;
AgentRequestMessageSourceType source1 = default;
AgentRequestMessageSourceType source2 = default;
// Act
bool result = source1 != source2;
@@ -429,34 +398,6 @@ public sealed class AgentRequestMessageSourceTypeTests
Assert.False(result);
}
[Fact]
public void InequalityOperator_WithLeftNull_ReturnsTrue()
{
// Arrange
AgentRequestMessageSourceType? source1 = null;
AgentRequestMessageSourceType source2 = new("Test");
// Act
bool result = source1 != source2;
// Assert
Assert.True(result);
}
[Fact]
public void InequalityOperator_WithRightNull_ReturnsTrue()
{
// Arrange
AgentRequestMessageSourceType source1 = new("Test");
AgentRequestMessageSourceType? source2 = null;
// Act
bool result = source1 != source2;
// Assert
Assert.True(result);
}
[Fact]
public void InequalityOperator_DifferentStaticInstances_ReturnsTrue()
{
@@ -64,7 +64,7 @@ public sealed class ChatHistoryProviderExtensionsTests
Mock<ChatHistoryProvider> providerMock = new();
List<ChatMessage> requestMessages =
[
new(ChatRole.System, "System") { AdditionalProperties = new() { { AgentRequestMessageSourceType.AdditionalPropertiesKey, AgentRequestMessageSourceType.ChatHistory } } },
new(ChatRole.System, "System") { AdditionalProperties = new() { { AgentRequestMessageSourceAttribution.AdditionalPropertiesKey, new AgentRequestMessageSourceAttribution(AgentRequestMessageSourceType.ChatHistory, "TestSource") } } },
new(ChatRole.User, "Hello")
];
ChatHistoryProvider.InvokedContext context = new(s_mockAgent, s_mockSession, requestMessages)
@@ -114,9 +114,9 @@ public sealed class ChatHistoryProviderExtensionsTests
Mock<ChatHistoryProvider> providerMock = new();
List<ChatMessage> requestMessages =
[
new(ChatRole.System, "System") { AdditionalProperties = new() { { AgentRequestMessageSourceType.AdditionalPropertiesKey, AgentRequestMessageSourceType.ChatHistory } } },
new(ChatRole.System, "System") { AdditionalProperties = new() { { AgentRequestMessageSourceAttribution.AdditionalPropertiesKey, new AgentRequestMessageSourceAttribution(AgentRequestMessageSourceType.ChatHistory, "TestSource") } } },
new(ChatRole.User, "Hello"),
new(ChatRole.System, "Context") { AdditionalProperties = new() { { AgentRequestMessageSourceType.AdditionalPropertiesKey, AgentRequestMessageSourceType.AIContextProvider } } }
new(ChatRole.System, "Context") { AdditionalProperties = new() { { AgentRequestMessageSourceAttribution.AdditionalPropertiesKey, new AgentRequestMessageSourceAttribution(AgentRequestMessageSourceType.AIContextProvider, "TestContextSource") } } }
];
ChatHistoryProvider.InvokedContext context = new(s_mockAgent, s_mockSession, requestMessages);
@@ -157,7 +157,7 @@ public sealed class ChatHistoryProviderMessageFilterTests
var innerProviderMock = new Mock<ChatHistoryProvider>();
List<ChatMessage> requestMessages =
[
new(ChatRole.System, "System") { AdditionalProperties = new() { { AgentRequestMessageSourceType.AdditionalPropertiesKey, AgentRequestMessageSourceType.ChatHistory } } },
new(ChatRole.System, "System") { AdditionalProperties = new() { { AgentRequestMessageSourceAttribution.AdditionalPropertiesKey, new AgentRequestMessageSourceAttribution(AgentRequestMessageSourceType.ChatHistory, "TestSource") } } },
new(ChatRole.User, "Hello"),
];
var responseMessages = new List<ChatMessage> { new(ChatRole.Assistant, "Response") };
@@ -176,7 +176,7 @@ public sealed class ChatHistoryProviderMessageFilterTests
// Filter that modifies the context
ChatHistoryProvider.InvokedContext InvokedFilter(ChatHistoryProvider.InvokedContext ctx)
{
var modifiedRequestMessages = ctx.RequestMessages.Where(x => x.GetAgentRequestMessageSource() == AgentRequestMessageSourceType.External).Select(m => new ChatMessage(m.Role, $"[FILTERED] {m.Text}")).ToList();
var modifiedRequestMessages = ctx.RequestMessages.Where(x => x.GetAgentRequestMessageSourceType() == AgentRequestMessageSourceType.External).Select(m => new ChatMessage(m.Role, $"[FILTERED] {m.Text}")).ToList();
return new ChatHistoryProvider.InvokedContext(s_mockAgent, s_mockSession, modifiedRequestMessages)
{
ResponseMessages = ctx.ResponseMessages,
@@ -22,7 +22,7 @@ public class ChatHistoryProviderTests
#region InvokingAsync Message Stamping Tests
[Fact]
public async Task InvokingAsync_StampsMessagesWithSourceTypeAndSourceAsync()
public async Task InvokingAsync_StampsMessagesWithSourceTypeAndSourceIdAsync()
{
// Arrange
var provider = new TestChatHistoryProvider();
@@ -34,18 +34,18 @@ public class ChatHistoryProviderTests
// Assert
ChatMessage message = messages.Single();
Assert.NotNull(message.AdditionalProperties);
Assert.True(message.AdditionalProperties.TryGetValue(AgentRequestMessageSourceType.AdditionalPropertiesKey, out object? sourceType));
Assert.Equal(AgentRequestMessageSourceType.ChatHistory, sourceType);
Assert.True(message.AdditionalProperties.TryGetValue(AgentRequestMessageSource.AdditionalPropertiesKey, out object? source));
Assert.Equal(typeof(TestChatHistoryProvider).FullName, source);
Assert.True(message.AdditionalProperties.TryGetValue(AgentRequestMessageSourceAttribution.AdditionalPropertiesKey, out object? attribution));
var typedAttribution = Assert.IsType<AgentRequestMessageSourceAttribution>(attribution);
Assert.Equal(AgentRequestMessageSourceType.ChatHistory, typedAttribution.SourceType);
Assert.Equal(typeof(TestChatHistoryProvider).FullName, typedAttribution.SourceId);
}
[Fact]
public async Task InvokingAsync_WithCustomSourceName_StampsMessagesWithCustomSourceAsync()
public async Task InvokingAsync_WithCustomSourceId_StampsMessagesWithCustomSourceIdAsync()
{
// Arrange
const string CustomSourceName = "CustomHistorySource";
var provider = new TestChatHistoryProviderWithCustomSource(CustomSourceName);
const string CustomSourceId = "CustomHistorySource";
var provider = new TestChatHistoryProviderWithCustomSource(CustomSourceId);
var context = new ChatHistoryProvider.InvokingContext(s_mockAgent, s_mockSession, [new ChatMessage(ChatRole.User, "Request")]);
// Act
@@ -54,10 +54,10 @@ public class ChatHistoryProviderTests
// Assert
ChatMessage message = messages.Single();
Assert.NotNull(message.AdditionalProperties);
Assert.True(message.AdditionalProperties.TryGetValue(AgentRequestMessageSourceType.AdditionalPropertiesKey, out object? sourceType));
Assert.Equal(AgentRequestMessageSourceType.ChatHistory, sourceType);
Assert.True(message.AdditionalProperties.TryGetValue(AgentRequestMessageSource.AdditionalPropertiesKey, out object? source));
Assert.Equal(CustomSourceName, source);
Assert.True(message.AdditionalProperties.TryGetValue(AgentRequestMessageSourceAttribution.AdditionalPropertiesKey, out object? attribution));
var typedAttribution = Assert.IsType<AgentRequestMessageSourceAttribution>(attribution);
Assert.Equal(AgentRequestMessageSourceType.ChatHistory, typedAttribution.SourceType);
Assert.Equal(CustomSourceId, typedAttribution.SourceId);
}
[Fact]
@@ -73,10 +73,10 @@ public class ChatHistoryProviderTests
// Assert
ChatMessage message = messages.Single();
Assert.NotNull(message.AdditionalProperties);
Assert.True(message.AdditionalProperties.TryGetValue(AgentRequestMessageSourceType.AdditionalPropertiesKey, out object? sourceType));
Assert.Equal(AgentRequestMessageSourceType.ChatHistory, sourceType);
Assert.True(message.AdditionalProperties.TryGetValue(AgentRequestMessageSource.AdditionalPropertiesKey, out object? source));
Assert.Equal(typeof(TestChatHistoryProviderWithPreStampedMessages).FullName, source);
Assert.True(message.AdditionalProperties.TryGetValue(AgentRequestMessageSourceAttribution.AdditionalPropertiesKey, out object? attribution));
var typedAttribution = Assert.IsType<AgentRequestMessageSourceAttribution>(attribution);
Assert.Equal(AgentRequestMessageSourceType.ChatHistory, typedAttribution.SourceType);
Assert.Equal(typeof(TestChatHistoryProviderWithPreStampedMessages).FullName, typedAttribution.SourceId);
}
[Fact]
@@ -96,10 +96,10 @@ public class ChatHistoryProviderTests
foreach (ChatMessage message in messageList)
{
Assert.NotNull(message.AdditionalProperties);
Assert.True(message.AdditionalProperties.TryGetValue(AgentRequestMessageSourceType.AdditionalPropertiesKey, out object? sourceType));
Assert.Equal(AgentRequestMessageSourceType.ChatHistory, sourceType);
Assert.True(message.AdditionalProperties.TryGetValue(AgentRequestMessageSource.AdditionalPropertiesKey, out object? source));
Assert.Equal(typeof(TestChatHistoryProviderWithMultipleMessages).FullName, source);
Assert.True(message.AdditionalProperties.TryGetValue(AgentRequestMessageSourceAttribution.AdditionalPropertiesKey, out object? attribution));
var typedAttribution = Assert.IsType<AgentRequestMessageSourceAttribution>(attribution);
Assert.Equal(AgentRequestMessageSourceType.ChatHistory, typedAttribution.SourceType);
Assert.Equal(typeof(TestChatHistoryProviderWithMultipleMessages).FullName, typedAttribution.SourceId);
}
}
@@ -383,7 +383,7 @@ public class ChatHistoryProviderTests
private sealed class TestChatHistoryProviderWithCustomSource : ChatHistoryProvider
{
public TestChatHistoryProviderWithCustomSource(string sourceName) : base(sourceName)
public TestChatHistoryProviderWithCustomSource(string sourceId) : base(sourceId)
{
}
@@ -404,8 +404,7 @@ public class ChatHistoryProviderTests
var message = new ChatMessage(ChatRole.User, "Pre-stamped Message");
message.AdditionalProperties = new AdditionalPropertiesDictionary
{
[AgentRequestMessageSourceType.AdditionalPropertiesKey] = AgentRequestMessageSourceType.ChatHistory,
[AgentRequestMessageSource.AdditionalPropertiesKey] = this.GetType().FullName!
[AgentRequestMessageSourceAttribution.AdditionalPropertiesKey] = new AgentRequestMessageSourceAttribution(AgentRequestMessageSourceType.ChatHistory, this.GetType().FullName!)
};
return new([message]);
}
@@ -9,23 +9,23 @@ namespace Microsoft.Agents.AI.Abstractions.UnitTests;
/// </summary>
public sealed class ChatMessageExtensionsTests
{
#region GetAgentRequestMessageSource Tests
#region GetAgentRequestMessageSourceType Tests
[Fact]
public void GetAgentRequestMessageSource_WithNoAdditionalProperties_ReturnsExternal()
public void GetAgentRequestMessageSourceType_WithNoAdditionalProperties_ReturnsExternal()
{
// Arrange
ChatMessage message = new(ChatRole.User, "Hello");
// Act
AgentRequestMessageSourceType result = message.GetAgentRequestMessageSource();
AgentRequestMessageSourceType result = message.GetAgentRequestMessageSourceType();
// Assert
Assert.Equal(AgentRequestMessageSourceType.External, result);
}
[Fact]
public void GetAgentRequestMessageSource_WithNullAdditionalProperties_ReturnsExternal()
public void GetAgentRequestMessageSourceType_WithNullAdditionalProperties_ReturnsExternal()
{
// Arrange
ChatMessage message = new(ChatRole.User, "Hello")
@@ -34,14 +34,14 @@ public sealed class ChatMessageExtensionsTests
};
// Act
AgentRequestMessageSourceType result = message.GetAgentRequestMessageSource();
AgentRequestMessageSourceType result = message.GetAgentRequestMessageSourceType();
// Assert
Assert.Equal(AgentRequestMessageSourceType.External, result);
}
[Fact]
public void GetAgentRequestMessageSource_WithEmptyAdditionalProperties_ReturnsExternal()
public void GetAgentRequestMessageSourceType_WithEmptyAdditionalProperties_ReturnsExternal()
{
// Arrange
ChatMessage message = new(ChatRole.User, "Hello")
@@ -50,130 +50,130 @@ public sealed class ChatMessageExtensionsTests
};
// Act
AgentRequestMessageSourceType result = message.GetAgentRequestMessageSource();
AgentRequestMessageSourceType result = message.GetAgentRequestMessageSourceType();
// Assert
Assert.Equal(AgentRequestMessageSourceType.External, result);
}
[Fact]
public void GetAgentRequestMessageSource_WithExternalSource_ReturnsExternal()
public void GetAgentRequestMessageSourceType_WithExternalSourceType_ReturnsExternal()
{
// Arrange
ChatMessage message = new(ChatRole.User, "Hello")
{
AdditionalProperties = new AdditionalPropertiesDictionary
{
{ AgentRequestMessageSourceType.AdditionalPropertiesKey, AgentRequestMessageSourceType.External }
{ AgentRequestMessageSourceAttribution.AdditionalPropertiesKey, new AgentRequestMessageSourceAttribution(AgentRequestMessageSourceType.External, "TestSourceId") }
}
};
// Act
AgentRequestMessageSourceType result = message.GetAgentRequestMessageSource();
AgentRequestMessageSourceType result = message.GetAgentRequestMessageSourceType();
// Assert
Assert.Equal(AgentRequestMessageSourceType.External, result);
}
[Fact]
public void GetAgentRequestMessageSource_WithAIContextProviderSource_ReturnsAIContextProvider()
public void GetAgentRequestMessageSourceType_WithAIContextProviderSourceType_ReturnsAIContextProvider()
{
// Arrange
ChatMessage message = new(ChatRole.User, "Hello")
{
AdditionalProperties = new AdditionalPropertiesDictionary
{
{ AgentRequestMessageSourceType.AdditionalPropertiesKey, AgentRequestMessageSourceType.AIContextProvider }
{ AgentRequestMessageSourceAttribution.AdditionalPropertiesKey, new AgentRequestMessageSourceAttribution(AgentRequestMessageSourceType.AIContextProvider, "TestSourceId") }
}
};
// Act
AgentRequestMessageSourceType result = message.GetAgentRequestMessageSource();
AgentRequestMessageSourceType result = message.GetAgentRequestMessageSourceType();
// Assert
Assert.Equal(AgentRequestMessageSourceType.AIContextProvider, result);
}
[Fact]
public void GetAgentRequestMessageSource_WithChatHistorySource_ReturnsChatHistory()
public void GetAgentRequestMessageSourceType_WithChatHistorySourceType_ReturnsChatHistory()
{
// Arrange
ChatMessage message = new(ChatRole.User, "Hello")
{
AdditionalProperties = new AdditionalPropertiesDictionary
{
{ AgentRequestMessageSourceType.AdditionalPropertiesKey, AgentRequestMessageSourceType.ChatHistory }
{ AgentRequestMessageSourceAttribution.AdditionalPropertiesKey, new AgentRequestMessageSourceAttribution(AgentRequestMessageSourceType.ChatHistory, "TestSourceId") }
}
};
// Act
AgentRequestMessageSourceType result = message.GetAgentRequestMessageSource();
AgentRequestMessageSourceType result = message.GetAgentRequestMessageSourceType();
// Assert
Assert.Equal(AgentRequestMessageSourceType.ChatHistory, result);
}
[Fact]
public void GetAgentRequestMessageSource_WithCustomSource_ReturnsCustomSource()
public void GetAgentRequestMessageSourceType_WithCustomSourceType_ReturnsCustomSourceType()
{
// Arrange
AgentRequestMessageSourceType customSource = new("CustomSource");
AgentRequestMessageSourceType customSourceType = new("CustomSourceType");
ChatMessage message = new(ChatRole.User, "Hello")
{
AdditionalProperties = new AdditionalPropertiesDictionary
{
{ AgentRequestMessageSourceType.AdditionalPropertiesKey, customSource }
{ AgentRequestMessageSourceAttribution.AdditionalPropertiesKey, new AgentRequestMessageSourceAttribution(customSourceType, "TestSourceId") }
}
};
// Act
AgentRequestMessageSourceType result = message.GetAgentRequestMessageSource();
AgentRequestMessageSourceType result = message.GetAgentRequestMessageSourceType();
// Assert
Assert.Equal(customSource, result);
Assert.Equal("CustomSource", result.Value);
Assert.Equal(customSourceType, result);
Assert.Equal("CustomSourceType", result.Value);
}
[Fact]
public void GetAgentRequestMessageSource_WithWrongKeyType_ReturnsExternal()
public void GetAgentRequestMessageSourceType_WithWrongAttributionType_ReturnsExternal()
{
// Arrange
ChatMessage message = new(ChatRole.User, "Hello")
{
AdditionalProperties = new AdditionalPropertiesDictionary
{
{ AgentRequestMessageSourceType.AdditionalPropertiesKey, "NotAnAgentRequestMessageSource" }
{ AgentRequestMessageSourceAttribution.AdditionalPropertiesKey, "NotAnAgentRequestMessageSourceAttribution" }
}
};
// Act
AgentRequestMessageSourceType result = message.GetAgentRequestMessageSource();
AgentRequestMessageSourceType result = message.GetAgentRequestMessageSourceType();
// Assert
Assert.Equal(AgentRequestMessageSourceType.External, result);
}
[Fact]
public void GetAgentRequestMessageSource_WithNullValue_ReturnsExternal()
public void GetAgentRequestMessageSourceType_WithNullAttributionValue_ReturnsExternal()
{
// Arrange
ChatMessage message = new(ChatRole.User, "Hello")
{
AdditionalProperties = new AdditionalPropertiesDictionary
{
{ AgentRequestMessageSourceType.AdditionalPropertiesKey, null! }
{ AgentRequestMessageSourceAttribution.AdditionalPropertiesKey, null! }
}
};
// Act
AgentRequestMessageSourceType result = message.GetAgentRequestMessageSource();
AgentRequestMessageSourceType result = message.GetAgentRequestMessageSourceType();
// Assert
Assert.Equal(AgentRequestMessageSourceType.External, result);
}
[Fact]
public void GetAgentRequestMessageSource_WithMultipleProperties_ReturnsCorrectSource()
public void GetAgentRequestMessageSourceType_WithMultipleProperties_ReturnsCorrectSourceType()
{
// Arrange
ChatMessage message = new(ChatRole.User, "Hello")
@@ -181,17 +181,345 @@ public sealed class ChatMessageExtensionsTests
AdditionalProperties = new AdditionalPropertiesDictionary
{
{ "OtherProperty", "SomeValue" },
{ AgentRequestMessageSourceType.AdditionalPropertiesKey, AgentRequestMessageSourceType.ChatHistory },
{ AgentRequestMessageSourceAttribution.AdditionalPropertiesKey, new AgentRequestMessageSourceAttribution(AgentRequestMessageSourceType.ChatHistory, "TestSourceId") },
{ "AnotherProperty", 123 }
}
};
// Act
AgentRequestMessageSourceType result = message.GetAgentRequestMessageSource();
AgentRequestMessageSourceType result = message.GetAgentRequestMessageSourceType();
// Assert
Assert.Equal(AgentRequestMessageSourceType.ChatHistory, result);
}
#endregion
#region GetAgentRequestMessageSourceId Tests
[Fact]
public void GetAgentRequestMessageSourceId_WithNoAdditionalProperties_ReturnsNull()
{
// Arrange
ChatMessage message = new(ChatRole.User, "Hello");
// Act
string? result = message.GetAgentRequestMessageSourceId();
// Assert
Assert.Null(result);
}
[Fact]
public void GetAgentRequestMessageSourceId_WithNullAdditionalProperties_ReturnsNull()
{
// Arrange
ChatMessage message = new(ChatRole.User, "Hello")
{
AdditionalProperties = null
};
// Act
string? result = message.GetAgentRequestMessageSourceId();
// Assert
Assert.Null(result);
}
[Fact]
public void GetAgentRequestMessageSourceId_WithEmptyAdditionalProperties_ReturnsNull()
{
// Arrange
ChatMessage message = new(ChatRole.User, "Hello")
{
AdditionalProperties = new AdditionalPropertiesDictionary()
};
// Act
string? result = message.GetAgentRequestMessageSourceId();
// Assert
Assert.Null(result);
}
[Fact]
public void GetAgentRequestMessageSourceId_WithAttribution_ReturnsSourceId()
{
// Arrange
ChatMessage message = new(ChatRole.User, "Hello")
{
AdditionalProperties = new AdditionalPropertiesDictionary
{
{ AgentRequestMessageSourceAttribution.AdditionalPropertiesKey, new AgentRequestMessageSourceAttribution(AgentRequestMessageSourceType.AIContextProvider, "MyProvider.FullName") }
}
};
// Act
string? result = message.GetAgentRequestMessageSourceId();
// Assert
Assert.Equal("MyProvider.FullName", result);
}
[Fact]
public void GetAgentRequestMessageSourceId_WithDifferentSourceIds_ReturnsCorrectSourceId()
{
// Arrange
ChatMessage message = new(ChatRole.User, "Hello")
{
AdditionalProperties = new AdditionalPropertiesDictionary
{
{ AgentRequestMessageSourceAttribution.AdditionalPropertiesKey, new AgentRequestMessageSourceAttribution(AgentRequestMessageSourceType.ChatHistory, "CustomHistorySourceId") }
}
};
// Act
string? result = message.GetAgentRequestMessageSourceId();
// Assert
Assert.Equal("CustomHistorySourceId", result);
}
[Fact]
public void GetAgentRequestMessageSourceId_WithWrongAttributionType_ReturnsNull()
{
// Arrange
ChatMessage message = new(ChatRole.User, "Hello")
{
AdditionalProperties = new AdditionalPropertiesDictionary
{
{ AgentRequestMessageSourceAttribution.AdditionalPropertiesKey, "NotAnAgentRequestMessageSourceAttribution" }
}
};
// Act
string? result = message.GetAgentRequestMessageSourceId();
// Assert
Assert.Null(result);
}
[Fact]
public void GetAgentRequestMessageSourceId_WithNullAttributionValue_ReturnsNull()
{
// Arrange
ChatMessage message = new(ChatRole.User, "Hello")
{
AdditionalProperties = new AdditionalPropertiesDictionary
{
{ AgentRequestMessageSourceAttribution.AdditionalPropertiesKey, null! }
}
};
// Act
string? result = message.GetAgentRequestMessageSourceId();
// Assert
Assert.Null(result);
}
[Fact]
public void GetAgentRequestMessageSourceId_WithMultipleProperties_ReturnsCorrectSourceId()
{
// Arrange
ChatMessage message = new(ChatRole.User, "Hello")
{
AdditionalProperties = new AdditionalPropertiesDictionary
{
{ "OtherProperty", "SomeValue" },
{ AgentRequestMessageSourceAttribution.AdditionalPropertiesKey, new AgentRequestMessageSourceAttribution(AgentRequestMessageSourceType.External, "ExpectedSourceId") },
{ "AnotherProperty", 123 }
}
};
// Act
string? result = message.GetAgentRequestMessageSourceId();
// Assert
Assert.Equal("ExpectedSourceId", result);
}
#endregion
#region AsAgentRequestMessageSourcedMessage Tests
[Fact]
public void AsAgentRequestMessageSourcedMessage_WithNoAdditionalProperties_ReturnsClonesMessageWithAttribution()
{
// Arrange
ChatMessage message = new(ChatRole.User, "Hello");
// Act
ChatMessage result = message.AsAgentRequestMessageSourcedMessage(AgentRequestMessageSourceType.External, "TestSourceId");
// Assert
Assert.NotSame(message, result);
Assert.Equal(AgentRequestMessageSourceType.External, result.GetAgentRequestMessageSourceType());
Assert.Equal("TestSourceId", result.GetAgentRequestMessageSourceId());
}
[Fact]
public void AsAgentRequestMessageSourcedMessage_WithNullAdditionalProperties_ReturnsClonesMessageWithAttribution()
{
// Arrange
ChatMessage message = new(ChatRole.User, "Hello")
{
AdditionalProperties = null
};
// Act
ChatMessage result = message.AsAgentRequestMessageSourcedMessage(AgentRequestMessageSourceType.AIContextProvider, "ProviderSourceId");
// Assert
Assert.NotSame(message, result);
Assert.Equal(AgentRequestMessageSourceType.AIContextProvider, result.GetAgentRequestMessageSourceType());
Assert.Equal("ProviderSourceId", result.GetAgentRequestMessageSourceId());
}
[Fact]
public void AsAgentRequestMessageSourcedMessage_WithMatchingSourceTypeAndSourceId_ReturnsSameInstance()
{
// Arrange
ChatMessage message = new(ChatRole.User, "Hello")
{
AdditionalProperties = new AdditionalPropertiesDictionary
{
{ AgentRequestMessageSourceAttribution.AdditionalPropertiesKey, new AgentRequestMessageSourceAttribution(AgentRequestMessageSourceType.ChatHistory, "HistoryId") }
}
};
// Act
ChatMessage result = message.AsAgentRequestMessageSourcedMessage(AgentRequestMessageSourceType.ChatHistory, "HistoryId");
// Assert
Assert.Same(message, result);
}
[Fact]
public void AsAgentRequestMessageSourcedMessage_WithDifferentSourceType_ReturnsClonesMessageWithNewAttribution()
{
// Arrange
ChatMessage message = new(ChatRole.User, "Hello")
{
AdditionalProperties = new AdditionalPropertiesDictionary
{
{ AgentRequestMessageSourceAttribution.AdditionalPropertiesKey, new AgentRequestMessageSourceAttribution(AgentRequestMessageSourceType.External, "SourceId") }
}
};
// Act
ChatMessage result = message.AsAgentRequestMessageSourcedMessage(AgentRequestMessageSourceType.AIContextProvider, "SourceId");
// Assert
Assert.NotSame(message, result);
Assert.Equal(AgentRequestMessageSourceType.AIContextProvider, result.GetAgentRequestMessageSourceType());
Assert.Equal("SourceId", result.GetAgentRequestMessageSourceId());
}
[Fact]
public void AsAgentRequestMessageSourcedMessage_WithDifferentSourceId_ReturnsClonesMessageWithNewAttribution()
{
// Arrange
ChatMessage message = new(ChatRole.User, "Hello")
{
AdditionalProperties = new AdditionalPropertiesDictionary
{
{ AgentRequestMessageSourceAttribution.AdditionalPropertiesKey, new AgentRequestMessageSourceAttribution(AgentRequestMessageSourceType.External, "OriginalId") }
}
};
// Act
ChatMessage result = message.AsAgentRequestMessageSourcedMessage(AgentRequestMessageSourceType.External, "NewId");
// Assert
Assert.NotSame(message, result);
Assert.Equal(AgentRequestMessageSourceType.External, result.GetAgentRequestMessageSourceType());
Assert.Equal("NewId", result.GetAgentRequestMessageSourceId());
}
[Fact]
public void AsAgentRequestMessageSourcedMessage_WithDefaultNullSourceId_ReturnsClonesMessageWithNullSourceId()
{
// Arrange
ChatMessage message = new(ChatRole.User, "Hello");
// Act
ChatMessage result = message.AsAgentRequestMessageSourcedMessage(AgentRequestMessageSourceType.ChatHistory);
// Assert
Assert.NotSame(message, result);
Assert.Equal(AgentRequestMessageSourceType.ChatHistory, result.GetAgentRequestMessageSourceType());
Assert.Null(result.GetAgentRequestMessageSourceId());
}
[Fact]
public void AsAgentRequestMessageSourcedMessage_WithMatchingSourceTypeAndNullSourceId_ReturnsSameInstance()
{
// Arrange
ChatMessage message = new(ChatRole.User, "Hello")
{
AdditionalProperties = new AdditionalPropertiesDictionary
{
{ AgentRequestMessageSourceAttribution.AdditionalPropertiesKey, new AgentRequestMessageSourceAttribution(AgentRequestMessageSourceType.External, null) }
}
};
// Act
ChatMessage result = message.AsAgentRequestMessageSourcedMessage(AgentRequestMessageSourceType.External);
// Assert
Assert.Same(message, result);
}
[Fact]
public void AsAgentRequestMessageSourcedMessage_DoesNotModifyOriginalMessage()
{
// Arrange
ChatMessage message = new(ChatRole.User, "Hello");
// Act
ChatMessage result = message.AsAgentRequestMessageSourcedMessage(AgentRequestMessageSourceType.AIContextProvider, "ProviderId");
// Assert
Assert.Null(message.AdditionalProperties);
Assert.NotNull(result.AdditionalProperties);
Assert.Equal(AgentRequestMessageSourceType.AIContextProvider, result.GetAgentRequestMessageSourceType());
}
[Fact]
public void AsAgentRequestMessageSourcedMessage_WithWrongAttributionType_ReturnsClonesMessageWithNewAttribution()
{
// Arrange
ChatMessage message = new(ChatRole.User, "Hello")
{
AdditionalProperties = new AdditionalPropertiesDictionary
{
{ AgentRequestMessageSourceAttribution.AdditionalPropertiesKey, "NotAnAttribution" }
}
};
// Act
ChatMessage result = message.AsAgentRequestMessageSourcedMessage(AgentRequestMessageSourceType.External, "SourceId");
// Assert
Assert.NotSame(message, result);
Assert.Equal(AgentRequestMessageSourceType.External, result.GetAgentRequestMessageSourceType());
Assert.Equal("SourceId", result.GetAgentRequestMessageSourceId());
}
[Fact]
public void AsAgentRequestMessageSourcedMessage_PreservesMessageContent()
{
// Arrange
ChatMessage message = new(ChatRole.Assistant, "Test content");
// Act
ChatMessage result = message.AsAgentRequestMessageSourcedMessage(AgentRequestMessageSourceType.ChatHistory, "HistoryId");
// Assert
Assert.Equal(ChatRole.Assistant, result.Role);
Assert.Equal("Test content", result.Text);
}
#endregion
}
@@ -55,7 +55,7 @@ public class InMemoryChatHistoryProviderTests
var requestMessages = new List<ChatMessage>
{
new(ChatRole.User, "Hello"),
new(ChatRole.System, "additional context") { AdditionalProperties = new() { { AgentRequestMessageSourceType.AdditionalPropertiesKey, AgentRequestMessageSourceType.ChatHistory } } },
new(ChatRole.System, "additional context") { AdditionalProperties = new() { { AgentRequestMessageSourceAttribution.AdditionalPropertiesKey, new AgentRequestMessageSourceAttribution(AgentRequestMessageSourceType.ChatHistory, "TestSource") } } },
};
var responseMessages = new List<ChatMessage>
{
@@ -286,7 +286,7 @@ public sealed class CosmosChatHistoryProviderTests : IAsyncLifetime, IDisposable
new ChatMessage(ChatRole.User, "First message"),
new ChatMessage(ChatRole.Assistant, "Second message"),
new ChatMessage(ChatRole.User, "Third message"),
new ChatMessage(ChatRole.System, "System context message") { AdditionalProperties = new() { { AgentRequestMessageSourceType.AdditionalPropertiesKey, AgentRequestMessageSourceType.AIContextProvider } } }
new ChatMessage(ChatRole.System, "System context message") { AdditionalProperties = new() { { AgentRequestMessageSourceAttribution.AdditionalPropertiesKey, new AgentRequestMessageSourceAttribution(AgentRequestMessageSourceType.AIContextProvider, "TestSource") } } }
};
var responseMessages = new[]
{
@@ -478,7 +478,7 @@ public sealed class PurviewClientTests : IDisposable
private static ContentToProcess CreateValidContentToProcess()
{
var content = new PurviewTextContent("Test content");
var metadata = new ProcessConversationMetadata(content, "msg-123", false, "Test message");
var metadata = new ProcessConversationMetadata(content, "msg-123", false, "Test message", "test-correlation-id");
var activityMetadata = new ActivityMetadata(Activity.UploadText);
var deviceMetadata = new DeviceMetadata
{
@@ -21,42 +21,51 @@ public sealed class MediaInputTest(ITestOutputHelper output) : IntegrationTest(o
{
private const string WorkflowWithConversationFileName = "MediaInputConversation.yaml";
private const string WorkflowWithAutoSendFileName = "MediaInputAutoSend.yaml";
private const string PdfReference = "https://sample-files.com/downloads/documents/pdf/basic-text.pdf";
private const string ImageReference = "https://sample-files.com/downloads/images/jpg/web_optimized_1200x800_97kb.jpg";
private const string PdfReference = "https://sample-files.com/downloads/documents/pdf/basic-text.pdf";
[Theory]
[InlineData(ImageReference, "image/jpeg", true, Skip = "Failing due to agent service bug.")]
[InlineData(ImageReference, "image/jpeg", false, Skip = "Failing due to agent service bug.")]
[InlineData(ImageReference, "image/jpeg", true)]
[InlineData(ImageReference, "image/jpeg", false)]
public async Task ValidateFileUrlAsync(string fileSource, string mediaType, bool useConversation)
{
this.Output.WriteLine($"File: {ImageReference}");
// Arrange
this.Output.WriteLine($"File: {fileSource}");
// Act & Assert
await this.ValidateFileAsync(new UriContent(fileSource, mediaType), useConversation);
}
[Theory]
[InlineData(ImageReference, "image/jpeg", true)]
[InlineData(ImageReference, "image/jpeg", false, Skip = "Failing due to agent service bug.")]
[InlineData(ImageReference, "image/jpeg", false)]
[InlineData(PdfReference, "application/pdf", true)]
[InlineData(PdfReference, "application/pdf", false)]
public async Task ValidateFileDataAsync(string fileSource, string mediaType, bool useConversation)
{
// Arrange
byte[] fileData = await DownloadFileAsync(fileSource);
string encodedData = Convert.ToBase64String(fileData);
string fileUrl = $"data:{mediaType};base64,{encodedData}";
this.Output.WriteLine($"Content: {fileUrl.Substring(0, 112)}...");
this.Output.WriteLine($"Content: {fileUrl.Substring(0, Math.Min(112, fileUrl.Length))}...");
// Act & Assert
await this.ValidateFileAsync(new DataContent(fileUrl), useConversation);
}
[Theory]
[InlineData(PdfReference, "doc.pdf", true, Skip = "Failing due to agent service bug.")]
[InlineData(PdfReference, "doc.pdf", false, Skip = "Failing due to agent service bug.")]
[InlineData(PdfReference, "doc.pdf", true)]
[InlineData(PdfReference, "doc.pdf", false)]
public async Task ValidateFileUploadAsync(string fileSource, string documentName, bool useConversation)
{
// Arrange
byte[] fileData = await DownloadFileAsync(fileSource);
AIProjectClient client = new(this.TestEndpoint, new AzureCliCredential());
using MemoryStream contentStream = new(fileData);
OpenAIFileClient fileClient = client.GetProjectOpenAIClient().GetOpenAIFileClient();
OpenAIFile fileInfo = await fileClient.UploadFileAsync(contentStream, documentName, FileUploadPurpose.Assistants);
// Act & Assert
try
{
this.Output.WriteLine($"File: {fileInfo.Id}");
@@ -77,6 +86,7 @@ public sealed class MediaInputTest(ITestOutputHelper output) : IntegrationTest(o
private async Task ValidateFileAsync(AIContent fileContent, bool useConversation)
{
// Act
AgentProvider agentProvider = AgentProvider.Create(this.Configuration, AgentProvider.Names.Vision);
await agentProvider.CreateAgentsAsync().ConfigureAwait(false);
@@ -93,6 +103,8 @@ public sealed class MediaInputTest(ITestOutputHelper output) : IntegrationTest(o
WorkflowHarness harness = new(workflow, runId: Path.GetFileNameWithoutExtension(workflowFileName));
WorkflowEvents workflowEvents = await harness.RunWorkflowAsync(inputMessage).ConfigureAwait(false);
// Assert
Assert.Equal(useConversation ? 1 : 2, workflowEvents.ConversationEvents.Count);
this.Output.WriteLine("CONVERSATION: " + workflowEvents.ConversationEvents[0].ConversationId);
AgentResponseEvent agentResponseEvent = Assert.Single(workflowEvents.AgentResponseEvents);
@@ -10,7 +10,6 @@
"conversation_count": 1,
"min_action_count": 1,
"min_response_count": 1,
"min_message_count": 2,
"actions": {
"start": [
"invoke_poem"
@@ -10,7 +10,6 @@
"conversation_count": 1,
"min_action_count": 3,
"min_response_count": 3,
"min_message_count": 6,
"actions": {
"start": [
"invoke_analyst",
@@ -17,7 +17,7 @@ internal sealed class MockAgentProvider : Mock<WorkflowAgentProvider>
{
public IList<string> ExistingConversationIds { get; } = [];
public List<ChatMessage>? TestMessages { get; set; }
public List<ChatMessage> TestMessages { get; set; } = [];
public MockAgentProvider()
{
@@ -45,7 +45,7 @@ internal sealed class MockAgentProvider : Mock<WorkflowAgentProvider>
It.IsAny<string>(),
It.IsAny<ChatMessage>(),
It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(testMessages.First()));
.Returns<string, ChatMessage, CancellationToken>((conversationId, message, cancellationToken) => Task.FromResult(this.CaptureChatMessage(message)));
}
private string CreateConversationId()
@@ -56,6 +56,13 @@ internal sealed class MockAgentProvider : Mock<WorkflowAgentProvider>
return newConversationId;
}
private ChatMessage CaptureChatMessage(ChatMessage message)
{
this.TestMessages.Add(message);
return message;
}
private List<ChatMessage> CreateMessages()
{
// Create test messages
@@ -1,11 +1,14 @@
// Copyright (c) Microsoft. All rights reserved.
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Agents.AI.Workflows.Declarative.Extensions;
using Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
using Microsoft.Agents.AI.Workflows.Declarative.PowerFx;
using Microsoft.Agents.ObjectModel;
using Microsoft.Extensions.AI;
using Microsoft.PowerFx.Types;
using Xunit.Abstractions;
namespace Microsoft.Agents.AI.Workflows.Declarative.UnitTests.ObjectModel;
@@ -28,20 +31,64 @@ public sealed class AddConversationMessageExecutorTest(ITestOutputHelper output)
messageText: $"Hello from {role}");
}
[Theory]
[InlineData(AgentMessageRole.User)]
[InlineData(AgentMessageRole.Agent)]
public async Task AddMessageToWorkflowAsync(AgentMessageRole role)
{
// Arrange
this.State.Set(SystemScope.Names.ConversationId, FormulaValue.New("WorkflowConversationId"), VariableScopeNames.System);
// Act & Assert
await this.ExecuteTestAsync(
displayName: nameof(AddMessageToWorkflowAsync),
variableName: "TestMessage",
role: AgentMessageRoleWrapper.Get(role),
conversationId: "WorkflowConversationId",
messageText: $"Hello from {role}");
}
[Theory]
[InlineData(AgentMessageRole.User)]
[InlineData(AgentMessageRole.Agent)]
public async Task AddMessageWithMetadataAsync(AgentMessageRole role)
{
// Arrange
Dictionary<string, string> metadataValues =
new()
{
["Key1"] = "Value1",
["Key2"] = "Value2",
};
RecordDataValue metadataRecord = metadataValues.ToRecordValue();
// Act & Assert
await this.ExecuteTestAsync(
displayName: nameof(AddMessageWithMetadataAsync),
variableName: "TestMessage",
role: AgentMessageRoleWrapper.Get(role),
messageText: $"Hello from {role}",
metadata: metadataRecord);
}
private async Task ExecuteTestAsync(
string displayName,
string variableName,
AgentMessageRoleWrapper role,
string messageText)
string messageText,
string? conversationId = null,
RecordDataValue? metadata = null)
{
// Arrange
MockAgentProvider mockAgentProvider = new();
AddConversationMessage model = this.CreateModel(
this.FormatDisplayName(displayName),
FormatVariablePath(variableName),
"TestConversationId",
role,
messageText);
AddConversationMessage model =
this.CreateModel(
this.FormatDisplayName(displayName),
FormatVariablePath(variableName),
conversationId ?? "TestConversationId",
role,
messageText,
metadata);
AddConversationMessageExecutor action = new(model, mockAgentProvider.Object, this.State);
@@ -49,10 +96,15 @@ public sealed class AddConversationMessageExecutorTest(ITestOutputHelper output)
await this.ExecuteAsync(action);
// Assert
ChatMessage? testMessage = mockAgentProvider.TestMessages?.FirstOrDefault();
ChatMessage? testMessage = mockAgentProvider.TestMessages?.LastOrDefault();
Assert.NotNull(testMessage);
VerifyModel(model, action);
this.VerifyState(variableName, testMessage.ToRecord());
if (metadata is not null)
{
Assert.NotNull(testMessage.AdditionalProperties);
Assert.NotEmpty(testMessage.AdditionalProperties);
}
}
private AddConversationMessage CreateModel(
@@ -60,8 +112,15 @@ public sealed class AddConversationMessageExecutorTest(ITestOutputHelper output)
string messageVariable,
string conversationId,
AgentMessageRoleWrapper role,
string messageText)
string messageText,
RecordDataValue? metadata)
{
ObjectExpression<RecordDataValue>.Builder? metadataExpression = null;
if (metadata is not null)
{
metadataExpression = ObjectExpression<RecordDataValue>.Literal(metadata).ToBuilder();
}
AddConversationMessage.Builder actionBuilder =
new()
{
@@ -70,6 +129,7 @@ public sealed class AddConversationMessageExecutorTest(ITestOutputHelper output)
Message = PropertyPath.Create(messageVariable),
ConversationId = StringExpression.Literal(conversationId),
Role = role,
Metadata = metadataExpression,
};
actionBuilder.Content.Add(new AddConversationMessageContent.Builder
@@ -13,47 +13,91 @@ namespace Microsoft.Agents.AI.Workflows.Declarative.UnitTests.ObjectModel;
/// </summary>
public sealed class ClearAllVariablesExecutorTest(ITestOutputHelper output) : WorkflowActionExecutorTest(output)
{
[Fact]
public async Task ClearGlobalScopeAsync()
{
// Arrange
this.State.Set("GlobalVar", FormulaValue.New("Old value"), VariableScopeNames.Global);
// Act & Assert
await this.ExecuteTestAsync(
this.FormatDisplayName(nameof(ClearGlobalScopeAsync)),
VariablesToClear.AllGlobalVariables,
"GlobalVar",
VariableScopeNames.Global);
}
[Fact]
public async Task ClearWorkflowScopeAsync()
{
// Arrange
this.State.Set("NoVar", FormulaValue.New("Old value"));
this.State.Set("LocalVar", FormulaValue.New("Old value"));
// Act & Assert
await this.ExecuteTestAsync(
this.FormatDisplayName(nameof(ClearWorkflowScopeAsync)),
VariablesToClear.ConversationScopedVariables,
"LocalVar");
}
[Fact]
public async Task ClearUserScopeAsync()
{
// Arrange
this.State.Set("LocalVar", FormulaValue.New("Old value"));
// Act & Assert
await this.ExecuteTestAsync(
this.FormatDisplayName(nameof(ClearUserScopeAsync)),
VariablesToClear.UserScopedVariables,
"LocalVar",
expectedValue: FormulaValue.New("Old value"));
}
[Fact]
public async Task ClearWorkflowHistoryAsync()
{
// Arrange
this.State.Set("LocalVar", FormulaValue.New("Old value"));
// Act & Assert
await this.ExecuteTestAsync(
this.FormatDisplayName(nameof(ClearWorkflowHistoryAsync)),
VariablesToClear.ConversationHistory,
"LocalVar",
expectedValue: FormulaValue.New("Old value"));
}
private async Task ExecuteTestAsync(
string displayName,
VariablesToClear scope,
string variableName,
string variableScope = VariableScopeNames.Local,
FormulaValue? expectedValue = null)
{
// Arrange
ClearAllVariables model = this.CreateModel(
this.FormatDisplayName(displayName),
scope);
ClearAllVariablesExecutor action = new(model, this.State);
this.State.Bind();
ClearAllVariables model =
this.CreateModel(
this.FormatDisplayName(nameof(ClearWorkflowScopeAsync)),
VariablesToClear.ConversationScopedVariables);
// Act
ClearAllVariablesExecutor action = new(model, this.State);
await this.ExecuteAsync(action);
// Assert
VerifyModel(model, action);
this.VerifyUndefined("NoVar");
}
[Fact]
public async Task ClearUndefinedScopeAsync()
{
// Arrange
this.State.Set("NoVar", FormulaValue.New("Old value"));
this.State.Bind();
// Arrange
ClearAllVariables model =
this.CreateModel(
this.FormatDisplayName(nameof(ClearUndefinedScopeAsync)),
VariablesToClear.UserScopedVariables);
// Act
ClearAllVariablesExecutor action = new(model, this.State);
await this.ExecuteAsync(action);
// Assert
VerifyModel(model, action);
this.VerifyState("NoVar", FormulaValue.New("Old value"));
if (expectedValue is null)
{
this.VerifyUndefined(variableName, variableScope);
}
else
{
this.VerifyState(variableName, variableScope, expectedValue);
}
}
private ClearAllVariables CreateModel(string displayName, VariablesToClear variableTarget)
@@ -0,0 +1,345 @@
// Copyright (c) Microsoft. All rights reserved.
using System;
using System.Threading.Tasks;
using Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
using Microsoft.Agents.ObjectModel;
using Microsoft.PowerFx.Types;
using Xunit.Abstractions;
namespace Microsoft.Agents.AI.Workflows.Declarative.UnitTests.ObjectModel;
/// <summary>
/// Tests for <see cref="EditTableV2Executor"/>.
/// </summary>
public sealed class EditTableV2ExecutorTest(ITestOutputHelper output) : WorkflowActionExecutorTest(output)
{
[Fact]
public void InvalidModelNullItemsVariable()
{
// Arrange
EditTableV2 model = new EditTableV2.Builder
{
Id = this.CreateActionId(),
DisplayName = this.FormatDisplayName(nameof(InvalidModelNullItemsVariable)),
ItemsVariable = null,
ChangeType = new AddItemOperation.Builder
{
Value = new ValueExpression.Builder(ValueExpression.Literal(new StringDataValue("test")))
}.Build()
}.Build();
// Act, Assert
DeclarativeModelException exception = Assert.Throws<DeclarativeModelException>(() => new EditTableV2Executor(model, this.State));
Assert.Contains("required", exception.Message, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task InvalidModelVariableNotTableAsync()
{
// Arrange
this.State.Set("NotATable", FormulaValue.New("I am a string"));
EditTableV2 model = this.CreateModel(
nameof(InvalidModelVariableNotTableAsync),
"NotATable",
new AddItemOperation.Builder
{
Value = new ValueExpression.Builder(ValueExpression.Literal(new StringDataValue("test")))
}.Build());
EditTableV2Executor action = new(model, this.State);
// Act & Assert
await Assert.ThrowsAsync<DeclarativeActionException>(async () => await this.ExecuteAsync(action));
}
[Fact]
public async Task InvalidModelAddItemOperationNullValueAsync()
{
// Arrange
EditTableV2 model = new EditTableV2.Builder
{
Id = this.CreateActionId(),
DisplayName = this.FormatDisplayName(nameof(InvalidModelAddItemOperationNullValueAsync)),
ItemsVariable = PropertyPath.Create(FormatVariablePath("TestTable")),
ChangeType = new AddItemOperation.Builder
{
Value = null
}.Build()
}.Build();
RecordType recordType = RecordType.Empty().Add("Value", FormulaType.String);
TableValue tableValue = FormulaValue.NewTable(recordType);
this.State.Set("TestTable", tableValue);
// Act, Assert
EditTableV2Executor action = new(model, this.State);
await Assert.ThrowsAsync<DeclarativeActionException>(async () => await this.ExecuteAsync(action));
}
[Fact]
public async Task InvalidModelRemoveItemOperationNullValueAsync()
{
// Arrange
EditTableV2 model = new EditTableV2.Builder
{
Id = this.CreateActionId(),
DisplayName = this.FormatDisplayName(nameof(InvalidModelRemoveItemOperationNullValueAsync)),
ItemsVariable = PropertyPath.Create(FormatVariablePath("TestTable")),
ChangeType = new RemoveItemOperation.Builder
{
Value = null
}.Build()
}.Build();
RecordType recordType = RecordType.Empty().Add("Value", FormulaType.String);
TableValue tableValue = FormulaValue.NewTable(recordType);
this.State.Set("TestTable", tableValue);
// Act, Assert
EditTableV2Executor action = new(model, this.State);
await Assert.ThrowsAsync<DeclarativeActionException>(async () => await this.ExecuteAsync(action));
}
[Fact]
public async Task RemoveItemOperationNonTableValueAsync()
{
// Arrange
RecordType recordType = RecordType.Empty().Add("Value", FormulaType.String);
RecordValue record1 = FormulaValue.NewRecordFromFields(recordType, new NamedValue("Value", FormulaValue.New("Item1")));
TableValue tableValue = FormulaValue.NewTable(recordType, record1);
this.State.Set("TestTable", tableValue);
// Set a string value instead of a table for removal
this.State.Set("RemoveItems", FormulaValue.New("NotATable"));
EditTableV2 model = new EditTableV2.Builder
{
Id = this.CreateActionId(),
DisplayName = this.FormatDisplayName(nameof(RemoveItemOperationNonTableValueAsync)),
ItemsVariable = PropertyPath.Create(FormatVariablePath("TestTable")),
ChangeType = new RemoveItemOperation.Builder
{
Value = new ValueExpression.Builder(ValueExpression.Variable(PropertyPath.TopicVariable("RemoveItems")))
}.Build()
}.Build();
// Act
EditTableV2Executor action = new(model, this.State);
await this.ExecuteAsync(action);
// Assert: When the remove value is not a table, no removal occurs, so the table should be unchanged
FormulaValue value = this.State.Get("TestTable");
Assert.IsAssignableFrom<TableValue>(value);
TableValue resultTable = (TableValue)value;
Assert.Single(resultTable.Rows);
}
[Fact]
public async Task AddItemOperationWithSingleFieldRecordAsync()
{
// Arrange: Create an empty table with single field
RecordType recordType = RecordType.Empty().Add("Name", FormulaType.String);
TableValue tableValue = FormulaValue.NewTable(recordType);
this.State.Set("TestTable", tableValue);
// Arrange, Act, Assert
await this.ExecuteTestAsync<RecordValue>(
displayName: nameof(AddItemOperationWithSingleFieldRecordAsync),
variableName: "TestTable",
changeType: this.CreateAddItemOperation(new RecordDataValue.Builder
{
Properties =
{
["Name"] = new StringDataValue("John")
}
}.Build()),
verifyAction: (variableName, recordValue) =>
Assert.Equal("John", recordValue.GetField("Name").ToObject())
);
}
[Fact]
public async Task AddItemOperationWithScalarValueAsync()
{
// Arrange: Create an empty table with single field
RecordType recordType = RecordType.Empty().Add("Value", FormulaType.String);
TableValue tableValue = FormulaValue.NewTable(recordType);
this.State.Set("TestTable", tableValue);
// Act & Assert
await this.ExecuteTestAsync<RecordValue>(
displayName: nameof(AddItemOperationWithScalarValueAsync),
variableName: "TestTable",
changeType: this.CreateAddItemOperation(new StringDataValue("TestValue")),
verifyAction: (variableName, recordValue) =>
Assert.Equal("TestValue", recordValue.GetField("Value").ToObject())
);
}
[Fact]
public async Task ClearItemsOperationAsync()
{
// Arrange: Create a table with some items
RecordType recordType = RecordType.Empty().Add("Value", FormulaType.String);
RecordValue record1 = FormulaValue.NewRecordFromFields(recordType, new NamedValue("Value", FormulaValue.New("Item1")));
RecordValue record2 = FormulaValue.NewRecordFromFields(recordType, new NamedValue("Value", FormulaValue.New("Item2")));
TableValue tableValue = FormulaValue.NewTable(recordType, record1, record2);
this.State.Set("TestTable", tableValue);
// Act & Assert
await this.ExecuteTestAsync<BlankValue>(
displayName: nameof(ClearItemsOperationAsync),
variableName: "TestTable",
changeType: new ClearItemsOperation.Builder().Build());
}
[Fact]
public async Task RemoveItemOperationAsync()
{
// Arrange: Create a table with some items
RecordType recordType = RecordType.Empty().Add("Value", FormulaType.String);
RecordValue record1 = FormulaValue.NewRecordFromFields(recordType, new NamedValue("Value", FormulaValue.New("Item1")));
RecordValue record2 = FormulaValue.NewRecordFromFields(recordType, new NamedValue("Value", FormulaValue.New("Item2")));
TableValue tableValue = FormulaValue.NewTable(recordType, record1, record2);
this.State.Set("TestTable", tableValue);
// Act & Assert
await this.ExecuteTestAsync<BlankValue>(
displayName: nameof(RemoveItemOperationAsync),
variableName: "TestTable",
changeType: this.CreateRemoveItemOperation("Item1"));
}
[Fact]
public async Task TakeLastItemOperationWithItemsAsync()
{
// Arrange: Create a table with some items
RecordType recordType = RecordType.Empty().Add("Value", FormulaType.String);
RecordValue record1 = FormulaValue.NewRecordFromFields(recordType, new NamedValue("Value", FormulaValue.New("Item1")));
RecordValue record2 = FormulaValue.NewRecordFromFields(recordType, new NamedValue("Value", FormulaValue.New("Item2")));
RecordValue record3 = FormulaValue.NewRecordFromFields(recordType, new NamedValue("Value", FormulaValue.New("Item3")));
TableValue tableValue = FormulaValue.NewTable(recordType, record1, record2, record3);
this.State.Set("TestTable", tableValue);
// Arrange, Act, Assert
await this.ExecuteTestAsync<RecordValue>(
displayName: nameof(TakeLastItemOperationWithItemsAsync),
variableName: "TestTable",
changeType: new TakeLastItemOperation.Builder().Build(),
verifyAction: (variableName, recordValue) =>
Assert.Equal("Item3", recordValue.GetField("Value").ToObject())
);
}
[Fact]
public async Task TakeLastItemOperationEmptyTableAsync()
{
// Arrange: Create an empty table
RecordType recordType = RecordType.Empty().Add("Value", FormulaType.String);
TableValue tableValue = FormulaValue.NewTable(recordType);
this.State.Set("TestTable", tableValue);
// Arrange, Act, Assert
await this.ExecuteTestAsync<TableValue>(
displayName: nameof(TakeLastItemOperationEmptyTableAsync),
variableName: "TestTable",
changeType: new TakeLastItemOperation.Builder().Build());
}
[Fact]
public async Task TakeFirstItemOperationWithItemsAsync()
{
// Arrange: Create a table with some items
RecordType recordType = RecordType.Empty().Add("Value", FormulaType.String);
RecordValue record1 = FormulaValue.NewRecordFromFields(recordType, new NamedValue("Value", FormulaValue.New("Item1")));
RecordValue record2 = FormulaValue.NewRecordFromFields(recordType, new NamedValue("Value", FormulaValue.New("Item2")));
RecordValue record3 = FormulaValue.NewRecordFromFields(recordType, new NamedValue("Value", FormulaValue.New("Item3")));
TableValue tableValue = FormulaValue.NewTable(recordType, record1, record2, record3);
this.State.Set("TestTable", tableValue);
// Act & Assert
await this.ExecuteTestAsync<RecordValue>(
displayName: nameof(TakeFirstItemOperationWithItemsAsync),
variableName: "TestTable",
changeType: new TakeFirstItemOperation.Builder().Build(),
verifyAction: (variableName, recordValue) =>
Assert.Equal("Item1", recordValue.GetField("Value").ToObject())
);
}
[Fact]
public async Task TakeFirstItemOperationEmptyTableAsync()
{
// Arrange: Create an empty table
RecordType recordType = RecordType.Empty().Add("Value", FormulaType.String);
TableValue tableValue = FormulaValue.NewTable(recordType);
this.State.Set("TestTable", tableValue);
// Act & Assert
await this.ExecuteTestAsync<TableValue>(
displayName: nameof(TakeFirstItemOperationEmptyTableAsync),
variableName: "TestTable",
changeType: new TakeFirstItemOperation.Builder().Build());
}
private async Task ExecuteTestAsync<TValue>(
string displayName,
string variableName,
EditTableOperation changeType,
Action<string, TValue>? verifyAction = null) where TValue : FormulaValue
{
// Arrange
EditTableV2 model = this.CreateModel(displayName, variableName, changeType);
EditTableV2Executor action = new(model, this.State);
// Act
await this.ExecuteAsync(action);
// Assert
VerifyModel(model, action);
FormulaValue value = this.State.Get(variableName);
TValue typedValue = Assert.IsAssignableFrom<TValue>(value);
verifyAction?.Invoke(variableName, typedValue);
}
private EditTableV2 CreateModel(string displayName, string variableName, EditTableOperation changeType)
{
EditTableV2.Builder actionBuilder = new()
{
Id = this.CreateActionId(),
DisplayName = this.FormatDisplayName(displayName),
ItemsVariable = PropertyPath.Create(FormatVariablePath(variableName)),
ChangeType = changeType
};
return AssignParent<EditTableV2>(actionBuilder);
}
private AddItemOperation CreateAddItemOperation(DataValue value)
{
return new AddItemOperation.Builder
{
Value = new ValueExpression.Builder(ValueExpression.Literal(value))
}.Build();
}
private RemoveItemOperation CreateRemoveItemOperation(string itemValue)
{
// Create a table with the item to remove
RecordType recordType = RecordType.Empty().Add("Value", FormulaType.String);
RecordValue recordToRemove = FormulaValue.NewRecordFromFields(recordType, new NamedValue("Value", FormulaValue.New(itemValue)));
TableValue tableToRemove = FormulaValue.NewTable(recordType, recordToRemove);
// Store in state for expression evaluation
this.State.Set("RemoveItems", tableToRemove);
this.State.Bind();
return new RemoveItemOperation.Builder
{
Value = new ValueExpression.Builder(ValueExpression.Variable(PropertyPath.TopicVariable("RemoveItems")))
}.Build();
}
}
@@ -25,95 +25,71 @@ public sealed class ParseValueExecutorTest(ITestOutputHelper output) : WorkflowA
{"key1", new PropertyInfo.Builder() { Type = DataType.String } },
}
};
ParseValue model =
this.CreateModel(
this.FormatDisplayName(nameof(ParseRecordAsync)),
recordBuilder,
@"{ ""key1"": ""val1"" }");
// Act
ParseValueExecutor action = new(model, this.State);
await this.ExecuteAsync(action);
// Assert
VerifyModel(model, action);
this.VerifyState("Target", FormulaValue.NewRecordFromFields(new NamedValue("key1", FormulaValue.New("val1"))));
// Act & Assert
await this.ExecuteTestAsync(
this.FormatDisplayName(nameof(ParseRecordAsync)),
recordBuilder,
@"{ ""key1"": ""val1"" }",
FormulaValue.NewRecordFromFields(new NamedValue("key1", FormulaValue.New("val1"))));
}
[Fact]
public async Task ParseTableAsync()
{
// Arrange
RecordDataType.Builder recordBuilder =
new()
{
Properties =
{
{"key1", new PropertyInfo.Builder() { Type = DataType.String } },
}
};
ParseValue model =
this.CreateModel(
this.FormatDisplayName(nameof(ParseTableAsync)),
DataType.EmptyTable,
@"[""apple"",""banana"",""cat""]");
// Act
ParseValueExecutor action = new(model, this.State);
await this.ExecuteAsync(action);
// Assert
VerifyModel(model, action);
this.VerifyState("Target", FormulaValue.NewSingleColumnTable(FormulaValue.New("apple"), FormulaValue.New("banana"), FormulaValue.New("cat")));
// Arrange, Act & Assert
await this.ExecuteTestAsync(
this.FormatDisplayName(nameof(ParseTableAsync)),
DataType.EmptyTable,
@"[""apple"",""banana"",""cat""]",
FormulaValue.NewSingleColumnTable(FormulaValue.New("apple"), FormulaValue.New("banana"), FormulaValue.New("cat")));
}
[Fact]
public async Task ParseBooleanAsync()
{
// Arrange
ParseValue model =
this.CreateModel(
this.FormatDisplayName(nameof(ParseTableAsync)),
new BooleanDataType.Builder(),
"True");
// Act
ParseValueExecutor action = new(model, this.State);
await this.ExecuteAsync(action);
// Assert
VerifyModel(model, action);
this.VerifyState("Target", FormulaValue.New(true));
// Arrange, Act & Assert
await this.ExecuteTestAsync(
this.FormatDisplayName(nameof(ParseBooleanAsync)),
new BooleanDataType.Builder(),
"True",
FormulaValue.New(true));
}
[Fact]
public async Task ParseNumberAsync()
{
// Arrange
ParseValue model =
this.CreateModel(
this.FormatDisplayName(nameof(ParseNumberAsync)),
new NumberDataType.Builder(),
"42");
// Act
ParseValueExecutor action = new(model, this.State);
await this.ExecuteAsync(action);
// Assert
VerifyModel(model, action);
this.VerifyState("Target", FormulaValue.New(42));
// Arrange, Act & Assert
await this.ExecuteTestAsync(
this.FormatDisplayName(nameof(ParseNumberAsync)),
new NumberDataType.Builder(),
"42",
FormulaValue.New(42));
}
[Fact]
public async Task ParseStringAsync()
{
// Arrange
// Arrange, Act & Assert
await this.ExecuteTestAsync(
this.FormatDisplayName(nameof(ParseStringAsync)),
new StringDataType.Builder(),
"Hello, World!",
FormulaValue.New("Hello, World!"));
}
private async Task ExecuteTestAsync(
string displayName,
DataType.Builder dataBuilder,
string sourceText,
FormulaValue expectedValue)
{
ParseValue model =
this.CreateModel(
this.FormatDisplayName(nameof(ParseStringAsync)),
new StringDataType.Builder(),
"Hello, World!");
displayName,
"Target",
dataBuilder,
sourceText);
// Act
ParseValueExecutor action = new(model, this.State);
@@ -121,10 +97,14 @@ public sealed class ParseValueExecutorTest(ITestOutputHelper output) : WorkflowA
// Assert
VerifyModel(model, action);
this.VerifyState("Target", FormulaValue.New("Hello, World!"));
this.VerifyState("Target", expectedValue);
}
private ParseValue CreateModel(string displayName, DataType.Builder typeBuilder, string sourceText)
private ParseValue CreateModel(
string displayName,
string variableName,
DataType.Builder typeBuilder,
string sourceText)
{
ParseValue.Builder actionBuilder =
new()
@@ -132,7 +112,7 @@ public sealed class ParseValueExecutorTest(ITestOutputHelper output) : WorkflowA
Id = this.CreateActionId(),
DisplayName = this.FormatDisplayName(displayName),
ValueType = typeBuilder,
Variable = PropertyPath.TopicVariable("Target"),
Variable = PropertyPath.TopicVariable(variableName),
Value = new ValueExpression.Builder(ValueExpression.Literal(StringDataValue.Create(sourceText))),
};
@@ -63,7 +63,7 @@ public sealed class ResetVariableExecutorTest(ITestOutputHelper output) : Workfl
{
Id = this.CreateActionId(),
DisplayName = this.FormatDisplayName(displayName),
Variable = InitializablePropertyPath.Create(variablePath),
Variable = PropertyPath.Create(variablePath),
};
return AssignParent<ResetVariable>(actionBuilder);
@@ -1,5 +1,6 @@
// Copyright (c) Microsoft. All rights reserved.
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
using Microsoft.Agents.ObjectModel;
@@ -32,7 +33,6 @@ public sealed class SetMultipleVariablesExecutorTest(ITestOutputHelper output) :
// Arrange
this.State.Set("SourceNumber", FormulaValue.New(10));
this.State.Set("SourceText", FormulaValue.New("Hello"));
this.State.Bind();
// Act, Assert
await this.ExecuteTestAsync(
@@ -50,7 +50,6 @@ public sealed class SetMultipleVariablesExecutorTest(ITestOutputHelper output) :
// Arrange
this.State.Set("Source1", FormulaValue.New(123));
this.State.Set("Source2", FormulaValue.New("Reference"));
this.State.Bind();
// Act, Assert
await this.ExecuteTestAsync(
@@ -74,6 +73,19 @@ public sealed class SetMultipleVariablesExecutorTest(ITestOutputHelper output) :
]);
}
[Fact]
public async Task SetMultipleVariablesWithNullVariableAsync()
{
// Arrange, Act, Assert
await this.ExecuteTestAsync(
displayName: nameof(SetMultipleVariablesWithNullVariableAsync),
assignments: [
new AssignmentCase("NullVar1", null, FormulaValue.NewBlank()),
new AssignmentCase(null, new StringDataValue("NotNull"), FormulaValue.New("NotNull")),
new AssignmentCase("NullVar2", null, FormulaValue.NewBlank())
]);
}
[Fact]
public async Task SetMultipleVariablesUpdateExistingAsync()
{
@@ -116,9 +128,9 @@ public sealed class SetMultipleVariablesExecutorTest(ITestOutputHelper output) :
// Assert
VerifyModel(model, action);
foreach (AssignmentCase assignment in assignments)
foreach (AssignmentCase assignment in assignments.Where(a => a.VariableName != null))
{
this.VerifyState(assignment.VariableName, assignment.ExpectedValue);
this.VerifyState(assignment.VariableName!, assignment.ExpectedValue);
}
}
@@ -140,9 +152,15 @@ public sealed class SetMultipleVariablesExecutorTest(ITestOutputHelper output) :
_ => throw new System.ArgumentException($"Unsupported value type: {assignment.ValueExpression?.GetType().Name}")
};
InitializablePropertyPath? variablePath = null;
if (assignment.VariableName != null)
{
variablePath = PropertyPath.Create(FormatVariablePath(assignment.VariableName));
}
actionBuilder.Assignments.Add(new VariableAssignment.Builder()
{
Variable = PropertyPath.Create(FormatVariablePath(assignment.VariableName)),
Variable = variablePath,
Value = valueExpressionBuilder,
});
}
@@ -150,5 +168,5 @@ public sealed class SetMultipleVariablesExecutorTest(ITestOutputHelper output) :
return AssignParent<SetMultipleVariables>(actionBuilder);
}
private sealed record AssignmentCase(string VariableName, object? ValueExpression, FormulaValue ExpectedValue);
private sealed record AssignmentCase(string? VariableName, object? ValueExpression, FormulaValue ExpectedValue);
}
@@ -16,20 +16,11 @@ public sealed class SetTextVariableExecutorTest(ITestOutputHelper output) : Work
[Fact]
public async Task SetLiteralValueAsync()
{
// Arrange
SetTextVariable model =
this.CreateModel(
// Arrange, Act & Assert
await this.ExecuteTestAsync(
this.FormatDisplayName(nameof(SetLiteralValueAsync)),
FormatVariablePath("TextVar"),
"Text variable value");
// Act
SetTextVariableExecutor action = new(model, this.State);
await this.ExecuteAsync(action);
// Assert
VerifyModel(model, action);
this.VerifyState("TextVar", FormulaValue.New("Text variable value"));
"TextVar",
"New value");
}
[Fact]
@@ -38,11 +29,24 @@ public sealed class SetTextVariableExecutorTest(ITestOutputHelper output) : Work
// Arrange
this.State.Set("TextVar", FormulaValue.New("Old value"));
// Act & Assert
await this.ExecuteTestAsync(
this.FormatDisplayName(nameof(UpdateExistingValueAsync)),
"TextVar",
"New value");
}
private async Task ExecuteTestAsync(
string displayName,
string variableName,
string textValue)
{
// Arrange
SetTextVariable model =
this.CreateModel(
this.FormatDisplayName(nameof(UpdateExistingValueAsync)),
FormatVariablePath("TextVar"),
"New value");
displayName,
variableName,
textValue);
// Act
SetTextVariableExecutor action = new(model, this.State);
@@ -50,7 +54,7 @@ public sealed class SetTextVariableExecutorTest(ITestOutputHelper output) : Work
// Assert
VerifyModel(model, action);
this.VerifyState("TextVar", FormulaValue.New("New value"));
this.VerifyState(variableName, FormulaValue.New(textValue));
}
private SetTextVariable CreateModel(string displayName, string variablePath, string textValue)
@@ -60,7 +64,7 @@ public sealed class SetTextVariableExecutorTest(ITestOutputHelper output) : Work
{
Id = this.CreateActionId(),
DisplayName = this.FormatDisplayName(displayName),
Variable = InitializablePropertyPath.Create(variablePath),
Variable = PropertyPath.Create(FormatVariablePath(variablePath)),
Value = TemplateLine.Parse(textValue),
};
@@ -92,7 +92,6 @@ public sealed class SetVariableExecutorTest(ITestOutputHelper output) : Workflow
{
// Arrange
this.State.Set("Source", FormulaValue.New(true));
this.State.Bind();
ValueExpression.Builder expressionBuilder = new(ValueExpression.Variable(PropertyPath.TopicVariable("Source")));
@@ -109,7 +108,6 @@ public sealed class SetVariableExecutorTest(ITestOutputHelper output) : Workflow
{
// Arrange
this.State.Set("Source", FormulaValue.New(321));
this.State.Bind();
ValueExpression.Builder expressionBuilder = new(ValueExpression.Variable(PropertyPath.TopicVariable("Source")));
@@ -126,7 +124,6 @@ public sealed class SetVariableExecutorTest(ITestOutputHelper output) : Workflow
{
// Arrange
this.State.Set("Source", FormulaValue.New("Test"));
this.State.Bind();
ValueExpression.Builder expressionBuilder = new(ValueExpression.Variable(PropertyPath.TopicVariable("Source")));
@@ -196,7 +193,7 @@ public sealed class SetVariableExecutorTest(ITestOutputHelper output) : Workflow
{
Id = this.CreateActionId(),
DisplayName = this.FormatDisplayName(displayName),
Variable = InitializablePropertyPath.Create(variablePath),
Variable = PropertyPath.Create(variablePath),
Value = valueExpression,
};
@@ -27,6 +27,8 @@ public abstract class WorkflowActionExecutorTest(ITestOutputHelper output) : Wor
internal async Task<WorkflowEvent[]> ExecuteAsync(DeclarativeActionExecutor executor)
{
this.State.Bind();
TestWorkflowExecutor workflowExecutor = new();
WorkflowBuilder workflowBuilder = new(workflowExecutor);
workflowBuilder.AddEdge(workflowExecutor, executor);
+3 -3
View File
@@ -69,7 +69,7 @@ def equal(arg1: str, arg2: str) -> bool:
```python
# Core
from agent_framework import ChatAgent, ChatMessage, tool
from agent_framework import ChatAgent, Message, tool
# Components
from agent_framework.observability import enable_instrumentation
@@ -84,10 +84,10 @@ from agent_framework.azure import AzureOpenAIChatClient
Define `__all__` in each module. Avoid `from module import *` in `__init__.py` files:
```python
__all__ = ["ChatAgent", "ChatMessage", "ChatResponse"]
__all__ = ["ChatAgent", "Message", "ChatResponse"]
from ._agents import ChatAgent
from ._types import ChatMessage, ChatResponse
from ._types import Message, ChatResponse
```
## Performance Guidelines
+55 -3
View File
@@ -7,6 +7,57 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [1.0.0b260210] - 2026-02-10
### Added
- **agent-framework-core**: Add long-running agents and background responses support with `ContinuationToken` TypedDict, `background` option in `OpenAIResponsesOptions`, and continuation token propagation through response types ([#3808](https://github.com/microsoft/agent-framework/pull/3808))
- **agent-framework-core**: Add streaming support for code interpreter deltas ([#3775](https://github.com/microsoft/agent-framework/pull/3775))
- **agent-framework-core**: Add explicit input, output, and workflow_output parameters to `@handler`, `@executor` and `request_info` ([#3472](https://github.com/microsoft/agent-framework/pull/3472))
- **agent-framework-core**: Add explicit schema handling to `@tool` decorator ([#3734](https://github.com/microsoft/agent-framework/pull/3734))
- **agent-framework-core**: New session and context provider types ([#3763](https://github.com/microsoft/agent-framework/pull/3763))
- **agent-framework-purview**: Add tests to Purview package ([#3513](https://github.com/microsoft/agent-framework/pull/3513))
### Changed
- **agent-framework-core**: [BREAKING] Renamed core types for simpler API: `ChatAgent` → `Agent`, `RawChatAgent` → `RawAgent`, `ChatMessage` → `Message`, `ChatClientProtocol` → `SupportsChatGetResponse` ([#3747](https://github.com/microsoft/agent-framework/pull/3747))
- **agent-framework-core**: [BREAKING] Moved to a single `get_response` and `run` API ([#3379](https://github.com/microsoft/agent-framework/pull/3379))
- **agent-framework-core**: [BREAKING] Merge `send_responses` into `run` method ([#3720](https://github.com/microsoft/agent-framework/pull/3720))
- **agent-framework-core**: [BREAKING] Renamed `AgentRunContext` to `AgentContext` ([#3714](https://github.com/microsoft/agent-framework/pull/3714))
- **agent-framework-core**: [BREAKING] Renamed `AgentProtocol` to `SupportsAgentRun` ([#3717](https://github.com/microsoft/agent-framework/pull/3717))
- **agent-framework-core**: [BREAKING] Renamed next middleware parameter to `call_next` ([#3735](https://github.com/microsoft/agent-framework/pull/3735))
- **agent-framework-core**: [BREAKING] Standardize TypeVar naming convention (`TName` → `NameT`) ([#3770](https://github.com/microsoft/agent-framework/pull/3770))
- **agent-framework-core**: [BREAKING] Refactor workflow events to unified discriminated union pattern ([#3690](https://github.com/microsoft/agent-framework/pull/3690))
- **agent-framework-core**: [BREAKING] Refactor `SharedState` to `State` with sync methods and superstep caching ([#3667](https://github.com/microsoft/agent-framework/pull/3667))
- **agent-framework-core**: [BREAKING] Move single-config fluent methods to constructor parameters ([#3693](https://github.com/microsoft/agent-framework/pull/3693))
- **agent-framework-core**: [BREAKING] Types API Review improvements ([#3647](https://github.com/microsoft/agent-framework/pull/3647))
- **agent-framework-core**: [BREAKING] Fix workflow as agent streaming output ([#3649](https://github.com/microsoft/agent-framework/pull/3649))
- **agent-framework-orchestrations**: [BREAKING] Move orchestrations to dedicated package ([#3685](https://github.com/microsoft/agent-framework/pull/3685))
- **agent-framework-core**: [BREAKING] Remove workflow register factory methods; update tests and samples ([#3781](https://github.com/microsoft/agent-framework/pull/3781))
- **agent-framework-core**: Include sub-workflow structure in graph signature for checkpoint validation ([#3783](https://github.com/microsoft/agent-framework/pull/3783))
- **agent-framework-core**: Adjust workflows TypeVars from prefix to suffix naming convention ([#3661](https://github.com/microsoft/agent-framework/pull/3661))
- **agent-framework-purview**: Update CorrelationId ([#3745](https://github.com/microsoft/agent-framework/pull/3745))
- **agent-framework-anthropic**: Added internal kwargs filtering for Anthropic client ([#3544](https://github.com/microsoft/agent-framework/pull/3544))
- **agent-framework-github-copilot**: Updated instructions/system_message logic in GitHub Copilot agent ([#3625](https://github.com/microsoft/agent-framework/pull/3625))
- **agent-framework-mem0**: Disable mem0 telemetry by default ([#3506](https://github.com/microsoft/agent-framework/pull/3506))
### Fixed
- **agent-framework-core**: Fix workflow not pausing when agent calls declaration-only tool ([#3757](https://github.com/microsoft/agent-framework/pull/3757))
- **agent-framework-core**: Fix GroupChat orchestrator message cleanup issue ([#3712](https://github.com/microsoft/agent-framework/pull/3712))
- **agent-framework-core**: Fix HandoffBuilder silently dropping `context_provider` during agent cloning ([#3721](https://github.com/microsoft/agent-framework/pull/3721))
- **agent-framework-core**: Fix subworkflow duplicate request info events ([#3689](https://github.com/microsoft/agent-framework/pull/3689))
- **agent-framework-core**: Fix workflow cancellation not propagating to active executors ([#3663](https://github.com/microsoft/agent-framework/pull/3663))
- **agent-framework-core**: Filter `response_format` from MCP tool call kwargs ([#3494](https://github.com/microsoft/agent-framework/pull/3494))
- **agent-framework-core**: Fix broken Content API imports in Python samples ([#3639](https://github.com/microsoft/agent-framework/pull/3639))
- **agent-framework-core**: Potential fix for clear-text logging of sensitive information ([#3573](https://github.com/microsoft/agent-framework/pull/3573))
- **agent-framework-core**: Skip `model_deployment_name` validation for application endpoints ([#3621](https://github.com/microsoft/agent-framework/pull/3621))
- **agent-framework-azure-ai**: Fix AzureAIClient dropping agent instructions (Responses API) ([#3636](https://github.com/microsoft/agent-framework/pull/3636))
- **agent-framework-azure-ai**: Fix AzureAIAgentClient dropping agent instructions in sequential workflows ([#3563](https://github.com/microsoft/agent-framework/pull/3563))
- **agent-framework-ag-ui**: Fix AG-UI message handling and MCP tool double-call bug ([#3635](https://github.com/microsoft/agent-framework/pull/3635))
- **agent-framework-claude**: Handle API errors in `run_stream()` method ([#3653](https://github.com/microsoft/agent-framework/pull/3653))
- **agent-framework-claude**: Preserve `$defs` in JSON schema for nested Pydantic models ([#3655](https://github.com/microsoft/agent-framework/pull/3655))
## [1.0.0b260130] - 2026-01-30
### Added
@@ -268,7 +319,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed
- **agent-framework-core**: [BREAKING] Support Magentic agent tool call approvals and plan stalling HITL behavior (#2569)
- **agent-framework-core**: [BREAKING] Standardize orchestration outputs as list of `ChatMessage`; allow agent as group chat manager (#2291)
- **agent-framework-core**: [BREAKING] Standardize orchestration outputs as list of `Message`; allow agent as group chat manager (#2291)
- **agent-framework-core**: [BREAKING] Respond with `AgentRunResponse` including serialized structured output (#2285)
- **observability**: Use `executor_id` and `edge_group_id` as span names for clearer traces (#2538)
- **agent-framework-devui**: Add multimodal input support for workflows and refactor chat input (#2593)
@@ -314,7 +365,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **agent-framework-core**: Fix tool execution bleed-over in aiohttp/Bot Framework scenarios ([#2314](https://github.com/microsoft/agent-framework/pull/2314))
- **agent-framework-core**: `@ai_function` now correctly handles `self` parameter ([#2266](https://github.com/microsoft/agent-framework/pull/2266))
- **agent-framework-core**: Resolve string annotations in `FunctionExecutor` ([#2308](https://github.com/microsoft/agent-framework/pull/2308))
- **agent-framework-core**: Langfuse observability captures ChatAgent system instructions ([#2316](https://github.com/microsoft/agent-framework/pull/2316))
- **agent-framework-core**: Langfuse observability captures Agent system instructions ([#2316](https://github.com/microsoft/agent-framework/pull/2316))
- **agent-framework-core**: Incomplete URL substring sanitization fix ([#2274](https://github.com/microsoft/agent-framework/pull/2274))
- **observability**: Handle datetime serialization in tool results ([#2248](https://github.com/microsoft/agent-framework/pull/2248))
@@ -571,7 +622,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
For more information, see the [announcement blog post](https://devblogs.microsoft.com/foundry/introducing-microsoft-agent-framework-the-open-source-engine-for-agentic-ai-apps/).
[Unreleased]: https://github.com/microsoft/agent-framework/compare/python-1.0.0b260130...HEAD
[Unreleased]: https://github.com/microsoft/agent-framework/compare/python-1.0.0b260210...HEAD
[1.0.0b260210]: https://github.com/microsoft/agent-framework/compare/python-1.0.0b260130...python-1.0.0b260210
[1.0.0b260130]: https://github.com/microsoft/agent-framework/compare/python-1.0.0b260128...python-1.0.0b260130
[1.0.0b260128]: https://github.com/microsoft/agent-framework/compare/python-1.0.0b260127...python-1.0.0b260128
[1.0.0b260127]: https://github.com/microsoft/agent-framework/compare/python-1.0.0b260123...python-1.0.0b260127
+9 -9
View File
@@ -118,10 +118,10 @@ Prefer attributes over inheritance when parameters are mostly the same:
```python
# âś… Preferred - using attributes
from agent_framework import ChatMessage
from agent_framework import Message
user_msg = ChatMessage("user", ["Hello, world!"])
asst_msg = ChatMessage("assistant", ["Hello, world!"])
user_msg = Message("user", ["Hello, world!"])
asst_msg = Message("assistant", ["Hello, world!"])
# ❌ Not preferred - unnecessary inheritance
from agent_framework import UserMessage, AssistantMessage
@@ -157,7 +157,7 @@ The package follows a flat import structure:
- **Core**: Import directly from `agent_framework`
```python
from agent_framework import ChatAgent, tool
from agent_framework import Agent, tool
```
- **Components**: Import from `agent_framework.<component>`
@@ -381,12 +381,12 @@ def create_client(
Use Google-style docstrings for all public APIs:
```python
def create_agent(name: str, chat_client: ChatClientProtocol) -> Agent:
def create_agent(name: str, client: SupportsChatGetResponse) -> Agent:
"""Create a new agent with the specified configuration.
Args:
name: The name of the agent.
chat_client: The chat client to use for communication.
client: The chat client to use for communication.
Returns:
True if the strings are the same, False otherwise.
@@ -409,10 +409,10 @@ Define `__all__` in each module to explicitly declare the public API. Avoid usin
```python
# âś… Preferred - explicit __all__ and imports
__all__ = ["ChatAgent", "ChatMessage", "ChatResponse"]
__all__ = ["Agent", "Message", "ChatResponse"]
from ._agents import ChatAgent
from ._types import ChatMessage, ChatResponse
from ._agents import Agent
from ._types import Message, ChatResponse
# ❌ Avoid - star imports
from ._agents import *
+1 -1
View File
@@ -116,7 +116,7 @@ You will then configure the ChatClient class with the keyword argument `env_file
```python
from agent_framework.openai import OpenAIChatClient
chat_client = OpenAIChatClient(env_file_path="openai.env")
client = OpenAIChatClient(env_file_path="openai.env")
```
## Tests
+15 -15
View File
@@ -62,7 +62,7 @@ You can also override environment variables by explicitly passing configuration
```python
from agent_framework.azure import AzureOpenAIChatClient
chat_client = AzureOpenAIChatClient(
client = AzureOpenAIChatClient(
api_key='',
endpoint='',
deployment_name='',
@@ -78,12 +78,12 @@ Create agents and invoke them directly:
```python
import asyncio
from agent_framework import ChatAgent
from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient
async def main():
agent = ChatAgent(
chat_client=OpenAIChatClient(),
agent = Agent(
client=OpenAIChatClient(),
instructions="""
1) A robot may not injure a human being...
2) A robot must obey orders given it by human beings...
@@ -106,15 +106,15 @@ You can use the chat client classes directly for advanced workflows:
```python
import asyncio
from agent_framework import ChatMessage
from agent_framework import Message
from agent_framework.openai import OpenAIChatClient
async def main():
client = OpenAIChatClient()
messages = [
ChatMessage("system", ["You are a helpful assistant."]),
ChatMessage("user", ["Write a haiku about Agent Framework."])
Message("system", ["You are a helpful assistant."]),
Message("user", ["Write a haiku about Agent Framework."])
]
response = await client.get_response(messages)
@@ -140,7 +140,7 @@ import asyncio
from typing import Annotated
from random import randint
from pydantic import Field
from agent_framework import ChatAgent
from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient
@@ -162,8 +162,8 @@ def get_menu_specials() -> str:
async def main():
agent = ChatAgent(
chat_client=OpenAIChatClient(),
agent = Agent(
client=OpenAIChatClient(),
instructions="You are a helpful assistant that can provide weather and restaurant information.",
tools=[get_weather, get_menu_specials]
)
@@ -189,20 +189,20 @@ Coordinate multiple agents to collaborate on complex tasks using orchestration p
```python
import asyncio
from agent_framework import ChatAgent
from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient
async def main():
# Create specialized agents
writer = ChatAgent(
chat_client=OpenAIChatClient(),
writer = Agent(
client=OpenAIChatClient(),
name="Writer",
instructions="You are a creative content writer. Generate and refine slogans based on feedback."
)
reviewer = ChatAgent(
chat_client=OpenAIChatClient(),
reviewer = Agent(
client=OpenAIChatClient(),
name="Reviewer",
instructions="You are a critical reviewer. Provide detailed feedback on proposed slogans."
)
@@ -2,7 +2,7 @@
import importlib.metadata
from ._agent import A2AAgent
from ._agent import A2AAgent, A2AContinuationToken
try:
__version__ = importlib.metadata.version(__name__)
@@ -11,5 +11,6 @@ except importlib.metadata.PackageNotFoundError:
__all__ = [
"A2AAgent",
"A2AContinuationToken",
"__version__",
]
+149 -95
View File
@@ -7,7 +7,7 @@ import json
import re
import uuid
from collections.abc import AsyncIterable, Awaitable, Sequence
from typing import Any, Final, Literal, cast, overload
from typing import Any, Final, Literal, overload
import httpx
from a2a.client import Client, ClientConfig, ClientFactory, minimal_agent_card
@@ -18,8 +18,9 @@ from a2a.types import (
FilePart,
FileWithBytes,
FileWithUri,
Message,
Task,
TaskIdParams,
TaskQueryParams,
TaskState,
TextPart,
TransportProtocol,
@@ -32,23 +33,41 @@ from agent_framework import (
AgentResponseUpdate,
AgentThread,
BaseAgent,
ChatMessage,
Content,
ContinuationToken,
Message,
ResponseStream,
normalize_messages,
prepend_agent_framework_to_user_agent,
)
from agent_framework.observability import AgentTelemetryLayer
__all__ = ["A2AAgent"]
__all__ = ["A2AAgent", "A2AContinuationToken"]
URI_PATTERN = re.compile(r"^data:(?P<media_type>[^;]+);base64,(?P<base64_data>[A-Za-z0-9+/=]+)$")
class A2AContinuationToken(ContinuationToken):
"""Continuation token for A2A protocol long-running tasks."""
task_id: str
"""A2A protocol task ID."""
context_id: str
"""A2A protocol context ID."""
TERMINAL_TASK_STATES = [
TaskState.completed,
TaskState.failed,
TaskState.canceled,
TaskState.rejected,
]
IN_PROGRESS_TASK_STATES = [
TaskState.submitted,
TaskState.working,
TaskState.input_required,
TaskState.auth_required,
]
def _get_uri_data(uri: str) -> str:
@@ -63,7 +82,7 @@ class A2AAgent(AgentTelemetryLayer, BaseAgent):
"""Agent2Agent (A2A) protocol implementation.
Wraps an A2A Client to connect the Agent Framework with external A2A-compliant agents
via HTTP/JSON-RPC. Converts framework ChatMessages to A2A Messages on send, and converts
via HTTP/JSON-RPC. Converts framework Messages to A2A Messages on send, and converts
A2A responses (Messages/Tasks) back to framework types. Inherits BaseAgent capabilities
while managing the underlying A2A protocol communication.
@@ -189,107 +208,89 @@ class A2AAgent(AgentTelemetryLayer, BaseAgent):
@overload
def run(
self,
messages: str | ChatMessage | Sequence[str | ChatMessage] | None = None,
messages: str | Message | Sequence[str | Message] | None = None,
*,
stream: Literal[False] = ...,
thread: AgentThread | None = None,
continuation_token: A2AContinuationToken | None = None,
background: bool = False,
**kwargs: Any,
) -> Awaitable[AgentResponse[Any]]: ...
@overload
def run(
self,
messages: str | ChatMessage | Sequence[str | ChatMessage] | None = None,
messages: str | Message | Sequence[str | Message] | None = None,
*,
stream: Literal[True],
thread: AgentThread | None = None,
continuation_token: A2AContinuationToken | None = None,
background: bool = False,
**kwargs: Any,
) -> ResponseStream[AgentResponseUpdate, AgentResponse[Any]]: ...
def run(
self,
messages: str | ChatMessage | Sequence[str | ChatMessage] | None = None,
messages: str | Message | Sequence[str | Message] | None = None,
*,
stream: bool = False,
thread: AgentThread | None = None,
continuation_token: A2AContinuationToken | None = None,
background: bool = False,
**kwargs: Any,
) -> Awaitable[AgentResponse[Any]] | ResponseStream[AgentResponseUpdate, AgentResponse[Any]]:
"""Get a response from the agent.
This method returns the final result of the agent's execution
as a single AgentResponse object when stream=False. When stream=True,
it returns a ResponseStream that yields AgentResponseUpdate objects.
Args:
messages: The message(s) to send to the agent.
Keyword Args:
stream: Whether to stream the response. Defaults to False.
thread: The conversation thread associated with the message(s).
continuation_token: Optional token to resume a long-running task
instead of starting a new one.
background: When True, in-progress task updates surface continuation
tokens so the caller can poll or resubscribe later. When False
(default), the agent internally waits for the task to complete.
kwargs: Additional keyword arguments.
Returns:
When stream=False: An Awaitable[AgentResponse].
When stream=True: A ResponseStream of AgentResponseUpdate items.
"""
if continuation_token is not None:
a2a_stream: AsyncIterable[Any] = self.client.resubscribe(TaskIdParams(id=continuation_token["task_id"]))
else:
normalized_messages = normalize_messages(messages)
a2a_message = self._prepare_message_for_a2a(normalized_messages[-1])
a2a_stream = self.client.send_message(a2a_message)
response = ResponseStream(
self._map_a2a_stream(a2a_stream, background=background),
finalizer=AgentResponse.from_updates,
)
if stream:
return self._run_stream_impl(messages=messages, thread=thread, **kwargs)
return self._run_impl(messages=messages, thread=thread, **kwargs)
return response
return response.get_final_response()
async def _run_impl(
async def _map_a2a_stream(
self,
messages: str | ChatMessage | Sequence[str | ChatMessage] | None = None,
a2a_stream: AsyncIterable[Any],
*,
thread: AgentThread | None = None,
**kwargs: Any,
) -> AgentResponse[Any]:
"""Non-streaming implementation of run."""
# Collect all updates and use framework to consolidate updates into response
updates: list[AgentResponseUpdate] = []
async for update in self._stream_updates(messages, thread=thread, **kwargs):
updates.append(update)
return AgentResponse.from_updates(updates)
def _run_stream_impl(
self,
messages: str | ChatMessage | Sequence[str | ChatMessage] | None = None,
*,
thread: AgentThread | None = None,
**kwargs: Any,
) -> ResponseStream[AgentResponseUpdate, AgentResponse[Any]]:
"""Streaming implementation of run."""
def _finalize(updates: Sequence[AgentResponseUpdate]) -> AgentResponse[Any]:
return AgentResponse.from_updates(list(updates))
return ResponseStream(self._stream_updates(messages, thread=thread, **kwargs), finalizer=_finalize)
async def _stream_updates(
self,
messages: str | ChatMessage | Sequence[str | ChatMessage] | None = None,
*,
thread: AgentThread | None = None,
**kwargs: Any,
background: bool = False,
) -> AsyncIterable[AgentResponseUpdate]:
"""Internal method to stream updates from the A2A agent.
"""Map raw A2A protocol items to AgentResponseUpdates.
Args:
messages: The message(s) to send to the agent.
a2a_stream: The raw A2A event stream.
Keyword Args:
thread: The conversation thread associated with the message(s).
kwargs: Additional keyword arguments.
Yields:
AgentResponseUpdate items from the A2A agent.
background: When False, in-progress task updates are silently
consumed (the stream keeps iterating until a terminal state).
When True, they are yielded with a continuation token.
"""
normalized_messages = normalize_messages(messages)
a2a_message = self._prepare_message_for_a2a(normalized_messages[-1])
response_stream = self.client.send_message(a2a_message)
async for item in response_stream:
if isinstance(item, Message):
async for item in a2a_stream:
if isinstance(item, A2AMessage):
# Process A2A Message
contents = self._parse_contents_from_a2a(item.parts)
yield AgentResponseUpdate(
@@ -300,37 +301,86 @@ class A2AAgent(AgentTelemetryLayer, BaseAgent):
)
elif isinstance(item, tuple) and len(item) == 2: # ClientEvent = (Task, UpdateEvent)
task, _update_event = item
if isinstance(task, Task) and task.status.state in TERMINAL_TASK_STATES:
# Convert Task artifacts to ChatMessages and yield as separate updates
task_messages = self._parse_messages_from_task(task)
if task_messages:
for message in task_messages:
# Use the artifact's ID from raw_representation as message_id for unique identification
artifact_id = getattr(message.raw_representation, "artifact_id", None)
yield AgentResponseUpdate(
contents=message.contents,
role=message.role,
response_id=task.id,
message_id=artifact_id,
raw_representation=task,
)
else:
# Empty task
yield AgentResponseUpdate(
contents=[],
role="assistant",
response_id=task.id,
raw_representation=task,
)
if isinstance(task, Task):
for update in self._updates_from_task(task, background=background):
yield update
else:
# Unknown response type
msg = f"Only Message and Task responses are supported from A2A agents. Received: {type(item)}"
raise NotImplementedError(msg)
def _prepare_message_for_a2a(self, message: ChatMessage) -> A2AMessage:
"""Prepare a ChatMessage for the A2A protocol.
# ------------------------------------------------------------------
# Task helpers
# ------------------------------------------------------------------
Transforms Agent Framework ChatMessage objects into A2A protocol Messages by:
def _updates_from_task(self, task: Task, *, background: bool = False) -> list[AgentResponseUpdate]:
"""Convert an A2A Task into AgentResponseUpdate(s).
Terminal tasks produce updates from their artifacts/history.
In-progress tasks produce a continuation token update only when
``background=True``; otherwise they are silently skipped so the
caller keeps consuming the stream until completion.
"""
if task.status.state in TERMINAL_TASK_STATES:
task_messages = self._parse_messages_from_task(task)
if task_messages:
return [
AgentResponseUpdate(
contents=message.contents,
role=message.role,
response_id=task.id,
message_id=getattr(message.raw_representation, "artifact_id", None),
raw_representation=task,
)
for message in task_messages
]
return [AgentResponseUpdate(contents=[], role="assistant", response_id=task.id, raw_representation=task)]
if background and task.status.state in IN_PROGRESS_TASK_STATES:
token = self._build_continuation_token(task)
return [
AgentResponseUpdate(
contents=[],
role="assistant",
response_id=task.id,
continuation_token=token,
raw_representation=task,
)
]
return []
@staticmethod
def _build_continuation_token(task: Task) -> A2AContinuationToken | None:
"""Build an A2AContinuationToken from an A2A Task if it is still in progress."""
if task.status.state in IN_PROGRESS_TASK_STATES:
return A2AContinuationToken(task_id=task.id, context_id=task.context_id)
return None
async def poll_task(self, continuation_token: A2AContinuationToken) -> AgentResponse[Any]:
"""Poll for the current state of a long-running A2A task.
Unlike ``run(continuation_token=...)``, which resubscribes to the SSE
stream, this performs a single request to retrieve the task state.
Args:
continuation_token: A token previously obtained from a response's
``continuation_token`` field.
Returns:
An AgentResponse whose ``continuation_token`` is set when the task
is still in progress, or ``None`` when it has reached a terminal state.
"""
task_id = continuation_token["task_id"]
task = await self.client.get_task(TaskQueryParams(id=task_id))
updates = self._updates_from_task(task, background=True)
if updates:
return AgentResponse.from_updates(updates)
return AgentResponse(messages=[], response_id=task.id, raw_representation=task)
def _prepare_message_for_a2a(self, message: Message) -> A2AMessage:
"""Prepare a Message for the A2A protocol.
Transforms Agent Framework Message objects into A2A protocol Messages by:
- Converting all message contents to appropriate A2A Part types
- Mapping text content to TextPart objects
- Converting file references (URI/data/hosted_file) to FilePart objects
@@ -339,7 +389,7 @@ class A2AAgent(AgentTelemetryLayer, BaseAgent):
"""
parts: list[A2APart] = []
if not message.contents:
raise ValueError("ChatMessage.contents is empty; cannot convert to A2AMessage.")
raise ValueError("Message.contents is empty; cannot convert to A2AMessage.")
# Process ALL contents
for content in message.contents:
@@ -401,11 +451,15 @@ class A2AAgent(AgentTelemetryLayer, BaseAgent):
case _:
raise ValueError(f"Unknown content type: {content.type}")
# Exclude framework-internal keys (e.g. attribution) from wire metadata
internal_keys = {"_attribution"}
metadata = {k: v for k, v in message.additional_properties.items() if k not in internal_keys} or None
return A2AMessage(
role=A2ARole("user"),
parts=parts,
message_id=message.message_id or uuid.uuid4().hex,
metadata=cast(dict[str, Any], message.additional_properties),
metadata=metadata,
)
def _parse_contents_from_a2a(self, parts: Sequence[A2APart]) -> list[Content]:
@@ -457,9 +511,9 @@ class A2AAgent(AgentTelemetryLayer, BaseAgent):
raise ValueError(f"Unknown Part kind: {inner_part.kind}")
return contents
def _parse_messages_from_task(self, task: Task) -> list[ChatMessage]:
"""Parse A2A Task artifacts into ChatMessages with ASSISTANT role."""
messages: list[ChatMessage] = []
def _parse_messages_from_task(self, task: Task) -> list[Message]:
"""Parse A2A Task artifacts into Messages with ASSISTANT role."""
messages: list[Message] = []
if task.artifacts is not None:
for artifact in task.artifacts:
@@ -469,7 +523,7 @@ class A2AAgent(AgentTelemetryLayer, BaseAgent):
history_item = task.history[-1]
contents = self._parse_contents_from_a2a(history_item.parts)
messages.append(
ChatMessage(
Message(
role="assistant" if history_item.role == A2ARole.agent else "user",
contents=contents,
raw_representation=history_item,
@@ -478,10 +532,10 @@ class A2AAgent(AgentTelemetryLayer, BaseAgent):
return messages
def _parse_message_from_artifact(self, artifact: Artifact) -> ChatMessage:
"""Parse A2A Artifact into ChatMessage using part contents."""
def _parse_message_from_artifact(self, artifact: Artifact) -> Message:
"""Parse A2A Artifact into Message using part contents."""
contents = self._parse_contents_from_a2a(artifact.parts)
return ChatMessage(
return Message(
role="assistant",
contents=contents,
raw_representation=artifact,
+2 -2
View File
@@ -4,7 +4,7 @@ description = "A2A integration for Microsoft Agent Framework."
authors = [{ name = "Microsoft", email = "af-support@microsoft.com"}]
readme = "README.md"
requires-python = ">=3.10"
version = "1.0.0b260130"
version = "1.0.0b260210"
license-files = ["LICENSE"]
urls.homepage = "https://aka.ms/agent-framework"
urls.source = "https://github.com/microsoft/agent-framework/tree/main/python"
@@ -23,7 +23,7 @@ classifiers = [
"Typing :: Typed",
]
dependencies = [
"agent-framework-core>=1.0.0b260130",
"agent-framework-core>=1.0.0b260210",
"a2a-sdk>=0.3.5",
]
+203 -17
View File
@@ -12,23 +12,24 @@ from a2a.types import (
DataPart,
FilePart,
FileWithUri,
Message,
Part,
Task,
TaskState,
TaskStatus,
TextPart,
)
from a2a.types import Message as A2AMessage
from a2a.types import Role as A2ARole
from agent_framework import (
AgentResponse,
AgentResponseUpdate,
ChatMessage,
Content,
Message,
)
from agent_framework.a2a import A2AAgent
from pytest import fixture, raises
from agent_framework_a2a import A2AContinuationToken
from agent_framework_a2a._agent import _get_uri_data # type: ignore
@@ -38,6 +39,8 @@ class MockA2AClient:
def __init__(self) -> None:
self.call_count: int = 0
self.responses: list[Any] = []
self.resubscribe_responses: list[Any] = []
self.get_task_response: Task | None = None
def add_message_response(self, message_id: str, text: str, role: str = "agent") -> None:
"""Add a mock Message response."""
@@ -46,7 +49,7 @@ class MockA2AClient:
text_part = Part(root=TextPart(text=text))
# Create actual Message instance
message = Message(
message = A2AMessage(
message_id=message_id, role=A2ARole.agent if role == "agent" else A2ARole.user, parts=[text_part]
)
self.responses.append(message)
@@ -80,6 +83,18 @@ class MockA2AClient:
client_event = (task, update_event)
self.responses.append(client_event)
def add_in_progress_task_response(
self,
task_id: str,
context_id: str = "test-context",
state: TaskState = TaskState.working,
) -> None:
"""Add a mock in-progress Task response (non-terminal)."""
status = TaskStatus(state=state, message=None)
task = Task(id=task_id, context_id=context_id, status=status)
client_event = (task, None)
self.responses.append(client_event)
async def send_message(self, message: Any) -> AsyncIterator[Any]:
"""Mock send_message method that yields responses."""
self.call_count += 1
@@ -88,6 +103,22 @@ class MockA2AClient:
response = self.responses.pop(0)
yield response
async def resubscribe(self, request: Any) -> AsyncIterator[Any]:
"""Mock resubscribe method that yields responses."""
self.call_count += 1
for response in self.resubscribe_responses:
yield response
self.resubscribe_responses.clear()
async def get_task(self, request: Any) -> Task:
"""Mock get_task method that returns a task."""
self.call_count += 1
if self.get_task_response is not None:
return self.get_task_response
msg = "No get_task response configured"
raise ValueError(msg)
@fixture
def mock_a2a_client() -> MockA2AClient:
@@ -250,7 +281,7 @@ def test_parse_message_from_artifact(a2a_agent: A2AAgent) -> None:
result = a2a_agent._parse_message_from_artifact(artifact)
assert isinstance(result, ChatMessage)
assert isinstance(result, Message)
assert result.role == "assistant"
assert result.text == "Artifact content"
assert result.raw_representation == artifact
@@ -293,9 +324,9 @@ def test_parse_contents_from_a2a_conversion(a2a_agent: A2AAgent) -> None:
def test_prepare_message_for_a2a_with_error_content(a2a_agent: A2AAgent) -> None:
"""Test _prepare_message_for_a2a with ErrorContent."""
# Create ChatMessage with ErrorContent
# Create Message with ErrorContent
error_content = Content.from_error(message="Test error message")
message = ChatMessage(role="user", contents=[error_content])
message = Message(role="user", contents=[error_content])
# Convert to A2A message
a2a_message = a2a_agent._prepare_message_for_a2a(message)
@@ -308,9 +339,9 @@ def test_prepare_message_for_a2a_with_error_content(a2a_agent: A2AAgent) -> None
def test_prepare_message_for_a2a_with_uri_content(a2a_agent: A2AAgent) -> None:
"""Test _prepare_message_for_a2a with UriContent."""
# Create ChatMessage with UriContent
# Create Message with UriContent
uri_content = Content.from_uri(uri="http://example.com/file.pdf", media_type="application/pdf")
message = ChatMessage(role="user", contents=[uri_content])
message = Message(role="user", contents=[uri_content])
# Convert to A2A message
a2a_message = a2a_agent._prepare_message_for_a2a(message)
@@ -324,9 +355,9 @@ def test_prepare_message_for_a2a_with_uri_content(a2a_agent: A2AAgent) -> None:
def test_prepare_message_for_a2a_with_data_content(a2a_agent: A2AAgent) -> None:
"""Test _prepare_message_for_a2a with DataContent."""
# Create ChatMessage with DataContent (base64 data URI)
# Create Message with DataContent (base64 data URI)
data_content = Content.from_uri(uri="data:text/plain;base64,SGVsbG8gV29ybGQ=", media_type="text/plain")
message = ChatMessage(role="user", contents=[data_content])
message = Message(role="user", contents=[data_content])
# Convert to A2A message
a2a_message = a2a_agent._prepare_message_for_a2a(message)
@@ -339,11 +370,11 @@ def test_prepare_message_for_a2a_with_data_content(a2a_agent: A2AAgent) -> None:
def test_prepare_message_for_a2a_empty_contents_raises_error(a2a_agent: A2AAgent) -> None:
"""Test _prepare_message_for_a2a with empty contents raises ValueError."""
# Create ChatMessage with no contents
message = ChatMessage(role="user", contents=[])
# Create Message with no contents
message = Message(role="user", contents=[])
# Should raise ValueError for empty contents
with raises(ValueError, match="ChatMessage.contents is empty"):
with raises(ValueError, match="Message.contents is empty"):
a2a_agent._prepare_message_for_a2a(message)
@@ -401,12 +432,12 @@ async def test_context_manager_no_cleanup_when_no_http_client() -> None:
def test_prepare_message_for_a2a_with_multiple_contents() -> None:
"""Test conversion of ChatMessage with multiple contents."""
"""Test conversion of Message with multiple contents."""
agent = A2AAgent(client=MagicMock(), _http_client=None)
# Create message with multiple content types
message = ChatMessage(
message = Message(
role="user",
contents=[
Content.from_text(text="Here's the analysis:"),
@@ -458,12 +489,12 @@ def test_parse_contents_from_a2a_unknown_part_kind() -> None:
def test_prepare_message_for_a2a_with_hosted_file() -> None:
"""Test conversion of ChatMessage with HostedFileContent to A2A message."""
"""Test conversion of Message with HostedFileContent to A2A message."""
agent = A2AAgent(client=MagicMock(), _http_client=None)
# Create message with hosted file content
message = ChatMessage(
message = Message(
role="user",
contents=[Content.from_hosted_file(file_id="hosted://storage/document.pdf")],
)
@@ -598,3 +629,158 @@ def test_a2a_agent_initialization_with_timeout_parameter() -> None:
# Verify it's an httpx.Timeout object with our custom timeout applied to all components
assert isinstance(timeout_arg, httpx.Timeout)
# region Continuation Token Tests
async def test_working_task_emits_continuation_token(a2a_agent: A2AAgent, mock_a2a_client: MockA2AClient) -> None:
"""Test that a working (non-terminal) task yields an update with a continuation token when background=True."""
mock_a2a_client.add_in_progress_task_response("task-wip", context_id="ctx-1", state=TaskState.working)
response = await a2a_agent.run("Start long task", background=True)
assert isinstance(response, AgentResponse)
assert response.continuation_token is not None
assert response.continuation_token["task_id"] == "task-wip"
assert response.continuation_token["context_id"] == "ctx-1"
async def test_submitted_task_emits_continuation_token(a2a_agent: A2AAgent, mock_a2a_client: MockA2AClient) -> None:
"""Test that a submitted task yields a continuation token when background=True."""
mock_a2a_client.add_in_progress_task_response("task-sub", state=TaskState.submitted)
response = await a2a_agent.run("Submit task", background=True)
assert response.continuation_token is not None
assert response.continuation_token["task_id"] == "task-sub"
async def test_input_required_task_emits_continuation_token(
a2a_agent: A2AAgent, mock_a2a_client: MockA2AClient
) -> None:
"""Test that an input_required task yields a continuation token when background=True."""
mock_a2a_client.add_in_progress_task_response("task-input", state=TaskState.input_required)
response = await a2a_agent.run("Need input", background=True)
assert response.continuation_token is not None
assert response.continuation_token["task_id"] == "task-input"
async def test_working_task_no_token_without_background(a2a_agent: A2AAgent, mock_a2a_client: MockA2AClient) -> None:
"""Test that background=False (default) does not emit continuation tokens for in-progress tasks."""
mock_a2a_client.add_in_progress_task_response("task-fg", context_id="ctx-fg", state=TaskState.working)
response = await a2a_agent.run("Foreground task")
assert response.continuation_token is None
async def test_completed_task_has_no_continuation_token(a2a_agent: A2AAgent, mock_a2a_client: MockA2AClient) -> None:
"""Test that a completed task does not set a continuation token."""
mock_a2a_client.add_task_response("task-done", [{"id": "art-1", "content": "Result"}])
response = await a2a_agent.run("Quick task")
assert response.continuation_token is None
assert len(response.messages) == 1
assert response.messages[0].text == "Result"
async def test_streaming_emits_continuation_token(a2a_agent: A2AAgent, mock_a2a_client: MockA2AClient) -> None:
"""Test that streaming with background=True yields updates with continuation tokens."""
mock_a2a_client.add_in_progress_task_response("task-stream", context_id="ctx-s", state=TaskState.working)
updates: list[AgentResponseUpdate] = []
async for update in a2a_agent.run("Stream task", stream=True, background=True):
updates.append(update)
assert len(updates) == 1
assert updates[0].continuation_token is not None
assert updates[0].continuation_token["task_id"] == "task-stream"
assert updates[0].continuation_token["context_id"] == "ctx-s"
async def test_resume_via_continuation_token(a2a_agent: A2AAgent, mock_a2a_client: MockA2AClient) -> None:
"""Test that run() with continuation_token uses resubscribe instead of send_message."""
# Set up the resubscribe response (completed task)
status = TaskStatus(state=TaskState.completed, message=None)
artifact = Artifact(
artifact_id="art-resume",
name="result",
parts=[Part(root=TextPart(text="Resumed result"))],
)
task = Task(id="task-resume", context_id="ctx-r", status=status, artifacts=[artifact])
mock_a2a_client.resubscribe_responses.append((task, None))
token = A2AContinuationToken(task_id="task-resume", context_id="ctx-r")
response = await a2a_agent.run(continuation_token=token)
assert isinstance(response, AgentResponse)
assert len(response.messages) == 1
assert response.messages[0].text == "Resumed result"
assert response.continuation_token is None
async def test_resume_streaming_via_continuation_token(a2a_agent: A2AAgent, mock_a2a_client: MockA2AClient) -> None:
"""Test that streaming run() with continuation_token and background=True uses resubscribe."""
# Still working
status_wip = TaskStatus(state=TaskState.working, message=None)
task_wip = Task(id="task-rs", context_id="ctx-rs", status=status_wip)
# Then completed
status_done = TaskStatus(state=TaskState.completed, message=None)
artifact = Artifact(
artifact_id="art-rs",
name="result",
parts=[Part(root=TextPart(text="Stream resumed"))],
)
task_done = Task(id="task-rs", context_id="ctx-rs", status=status_done, artifacts=[artifact])
mock_a2a_client.resubscribe_responses.extend([(task_wip, None), (task_done, None)])
token = A2AContinuationToken(task_id="task-rs", context_id="ctx-rs")
updates: list[AgentResponseUpdate] = []
async for update in a2a_agent.run(stream=True, continuation_token=token, background=True):
updates.append(update)
# First update: in-progress with token, second: completed with content
assert len(updates) == 2
assert updates[0].continuation_token is not None
assert updates[0].continuation_token["task_id"] == "task-rs"
assert updates[1].continuation_token is None
assert updates[1].contents[0].text == "Stream resumed"
async def test_poll_task_in_progress(a2a_agent: A2AAgent, mock_a2a_client: MockA2AClient) -> None:
"""Test poll_task returns continuation token when task is still in progress."""
status = TaskStatus(state=TaskState.working, message=None)
mock_a2a_client.get_task_response = Task(id="task-poll", context_id="ctx-p", status=status)
token = A2AContinuationToken(task_id="task-poll", context_id="ctx-p")
response = await a2a_agent.poll_task(token)
assert response.continuation_token is not None
assert response.continuation_token["task_id"] == "task-poll"
async def test_poll_task_completed(a2a_agent: A2AAgent, mock_a2a_client: MockA2AClient) -> None:
"""Test poll_task returns result with no continuation token when task is complete."""
status = TaskStatus(state=TaskState.completed, message=None)
artifact = Artifact(
artifact_id="art-poll",
name="result",
parts=[Part(root=TextPart(text="Poll result"))],
)
mock_a2a_client.get_task_response = Task(
id="task-poll-done", context_id="ctx-pd", status=status, artifacts=[artifact]
)
token = A2AContinuationToken(task_id="task-poll-done", context_id="ctx-pd")
response = await a2a_agent.poll_task(token)
assert response.continuation_token is None
assert len(response.messages) == 1
assert response.messages[0].text == "Poll result"
# endregion
+6 -6
View File
@@ -14,15 +14,15 @@ pip install agent-framework-ag-ui
```python
from fastapi import FastAPI
from agent_framework import ChatAgent
from agent_framework import Agent
from agent_framework.azure import AzureOpenAIChatClient
from agent_framework.ag_ui import add_agent_framework_fastapi_endpoint
# Create your agent
agent = ChatAgent(
agent = Agent(
name="my_agent",
instructions="You are a helpful assistant.",
chat_client=AzureOpenAIChatClient(
client=AzureOpenAIChatClient(
endpoint="https://your-resource.openai.azure.com/",
deployment_name="gpt-4o-mini",
api_key="your-api-key",
@@ -58,7 +58,7 @@ The `AGUIChatClient` supports:
- Streaming and non-streaming responses
- Hybrid tool execution (client-side + server-side tools)
- Automatic thread management for conversation continuity
- Integration with `ChatAgent` for client-side history management
- Integration with `Agent` for client-side history management
## Documentation
@@ -91,7 +91,7 @@ The AG-UI endpoint does not enforce authentication by default. **For production
import os
from fastapi import Depends, FastAPI, HTTPException, Security
from fastapi.security import APIKeyHeader
from agent_framework import ChatAgent
from agent_framework import Agent
from agent_framework.ag_ui import add_agent_framework_fastapi_endpoint
# Configure API key authentication
@@ -104,7 +104,7 @@ async def verify_api_key(api_key: str | None = Security(API_KEY_HEADER)) -> None
raise HTTPException(status_code=401, detail="Invalid or missing API key")
# Create agent and app
agent = ChatAgent(name="my_agent", instructions="...", chat_client=...)
agent = Agent(name="my_agent", instructions="...", client=...)
app = FastAPI()
# Register endpoint WITH authentication
@@ -15,11 +15,11 @@ from typing import TYPE_CHECKING, Any, Generic, TypedDict, cast
import httpx
from agent_framework import (
BaseChatClient,
ChatMessage,
ChatResponse,
ChatResponseUpdate,
Content,
FunctionTool,
Message,
ResponseStream,
)
from agent_framework._middleware import ChatMiddlewareLayer
@@ -59,20 +59,20 @@ def _unwrap_server_function_call_contents(contents: MutableSequence[Content | di
contents[idx] = content.function_call # type: ignore[assignment, union-attr]
TBaseChatClient = TypeVar("TBaseChatClient", bound=type[BaseChatClient[Any]])
BaseChatClientT = TypeVar("BaseChatClientT", bound=type[BaseChatClient[Any]])
TAGUIChatOptions = TypeVar(
"TAGUIChatOptions",
AGUIChatOptionsT = TypeVar(
"AGUIChatOptionsT",
bound=TypedDict, # type: ignore[valid-type]
default="AGUIChatOptions",
covariant=True,
)
def _apply_server_function_call_unwrap(chat_client: TBaseChatClient) -> TBaseChatClient:
def _apply_server_function_call_unwrap(client: BaseChatClientT) -> BaseChatClientT:
"""Class decorator that unwraps server-side function calls after tool handling."""
original_get_response = chat_client.get_response
original_get_response = client.get_response
@wraps(original_get_response)
def response_wrapper(
@@ -105,17 +105,17 @@ def _apply_server_function_call_unwrap(chat_client: TBaseChatClient) -> TBaseCha
_unwrap_server_function_call_contents(cast(MutableSequence[Content | dict[str, Any]], update.contents))
return update
chat_client.get_response = response_wrapper # type: ignore[assignment]
return chat_client
client.get_response = response_wrapper # type: ignore[assignment]
return client
@_apply_server_function_call_unwrap
class AGUIChatClient(
ChatMiddlewareLayer[TAGUIChatOptions],
FunctionInvocationLayer[TAGUIChatOptions],
ChatTelemetryLayer[TAGUIChatOptions],
BaseChatClient[TAGUIChatOptions],
Generic[TAGUIChatOptions],
ChatMiddlewareLayer[AGUIChatOptionsT],
FunctionInvocationLayer[AGUIChatOptionsT],
ChatTelemetryLayer[AGUIChatOptionsT],
BaseChatClient[AGUIChatOptionsT],
Generic[AGUIChatOptionsT],
):
"""Chat client for communicating with AG-UI compliant servers.
@@ -130,8 +130,8 @@ class AGUIChatClient(
This client sends exactly the messages it receives to the server. It does NOT
automatically maintain conversation history. The server must handle history via thread_id.
For stateless servers: Use ChatAgent wrapper which will send full message history on each
request. However, even with ChatAgent, the server must echo back all context for the
For stateless servers: Use Agent wrapper which will send full message history on each
request. However, even with Agent, the server must echo back all context for the
agent to maintain history across turns.
Important: Tool Handling (Hybrid Execution - matches .NET)
@@ -140,7 +140,7 @@ class AGUIChatClient(
3. When LLM calls a client tool, function invocation executes it locally
4. Both client and server tools work together (hybrid pattern)
The wrapping ChatAgent's function invocation handles client tool execution
The wrapping Agent's function invocation handles client tool execution
automatically when the server's LLM decides to call them.
Examples:
@@ -162,18 +162,18 @@ class AGUIChatClient(
metadata={"thread_id": thread_id}
)
Recommended usage with ChatAgent (client manages history):
Recommended usage with Agent (client manages history):
.. code-block:: python
from agent_framework import ChatAgent
from agent_framework import Agent
from agent_framework.ag_ui import AGUIChatClient
client = AGUIChatClient(endpoint="http://localhost:8888/")
agent = ChatAgent(name="assistant", client=client)
agent = Agent(name="assistant", client=client)
thread = await agent.get_new_thread()
# ChatAgent automatically maintains history and sends full context
# Agent automatically maintains history and sends full context
response = await agent.run("Hello!", thread=thread)
response2 = await agent.run("How are you?", thread=thread)
@@ -282,9 +282,7 @@ class AGUIChatClient(
logger = get_logger()
logger.debug(f"[AGUIChatClient] Registered server placeholder: {tool_name}")
def _extract_state_from_messages(
self, messages: Sequence[ChatMessage]
) -> tuple[list[ChatMessage], dict[str, Any] | None]:
def _extract_state_from_messages(self, messages: Sequence[Message]) -> tuple[list[Message], dict[str, Any] | None]:
"""Extract state from last message if present.
Args:
@@ -319,11 +317,11 @@ class AGUIChatClient(
return list(messages), None
def _convert_messages_to_agui_format(self, messages: list[ChatMessage]) -> list[dict[str, Any]]:
def _convert_messages_to_agui_format(self, messages: list[Message]) -> list[dict[str, Any]]:
"""Convert Agent Framework messages to AG-UI format.
Args:
messages: List of ChatMessage objects
messages: List of Message objects
Returns:
List of AG-UI formatted message dictionaries
@@ -353,7 +351,7 @@ class AGUIChatClient(
def _inner_get_response(
self,
*,
messages: Sequence[ChatMessage],
messages: Sequence[Message],
stream: bool = False,
options: Mapping[str, Any],
**kwargs: Any,
@@ -393,7 +391,7 @@ class AGUIChatClient(
async def _streaming_impl(
self,
*,
messages: Sequence[ChatMessage],
messages: Sequence[Message],
options: Mapping[str, Any],
**kwargs: Any,
) -> AsyncIterable[ChatResponseUpdate]:
@@ -415,7 +413,7 @@ class AGUIChatClient(
agui_messages = self._convert_messages_to_agui_format(messages_to_send)
# Send client tools to server so LLM knows about them
# Client tools execute via ChatAgent's function invocation wrapper
# Client tools execute via Agent's function invocation wrapper
agui_tools = convert_tools_to_agui_format(options.get("tools"))
# Build set of client tool names (matches .NET clientToolSet)

Some files were not shown because too many files have changed in this diff Show More