-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathProgram.cs
261 lines (223 loc) · 7.24 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
using AutoGen.Core;
using AutoGen.OpenAI;
using AutoGen.OpenAI.Extension;
using Microsoft.SemanticKernel;
using System.ComponentModel;
using System.Text;
using Util;
var chatClient = ChatClientProvider.Create("gpt-4o-mini");
// Initialize the chess board [3, 3]
// 0: empty, 1: X, 2: O
// Define the needed tools
// 1. Tool for getting legal moves
// 2. Tool for making a move on the board
var board = new TicTacToe(new int[3, 3]);
var toolMiddleware = new FunctionCallMiddleware(
functions:
[
board.DisplayBoardFunctionContract,
board.MakeMoveFunctionContract,
board.GetLegalMovesFunctionContract,
],
functionMap: new Dictionary<string, Func<string, Task<string>>>
{
{ board.DisplayBoardFunctionContract.Name!, board.DisplayBoardWrapper },
{ board.MakeMoveFunctionContract.Name!, board.MakeMoveWrapper },
{ board.GetLegalMovesFunctionContract.Name!, board.GetLegalMovesWrapper },
});
// Create agents
// You will create the player agents for the tic-tac-toe game.
var nestMiddleware = new NestMiddleware();
var playerX = new OpenAIChatAgent(
chatClient: chatClient,
name: "Player_X",
systemMessage: """
You are Player X. You are playing Tic-Tac-Toe against Player O.
You can make a move by providing the row and column number.
The board is 3x3, and the row and column number should be between 0 and 2.
First check the status, then get legal moves, and finally make a move.
""")
.RegisterMessageConnector()
.RegisterMiddleware(toolMiddleware)
.RegisterPrintMessage()
.RegisterMiddleware(nestMiddleware);
var playerO = new OpenAIChatAgent(
chatClient: chatClient,
name: "Player_O",
systemMessage: """
You are Player O. You are playing Tic-Tac-Toe against Player X.
You can make a move by providing the row and column number.
The board is 3x3, and the row and column number should be between 0 and 2.
First check the status, then get legal moves, and finally make a move.
""")
.RegisterMessageConnector()
.RegisterMiddleware(toolMiddleware)
.RegisterPrintMessage()
.RegisterMiddleware(nestMiddleware);
// Start the game
var conversationHistory = new List<IMessage>()
{
new TextMessage(Role.Assistant, "You start first", from: playerX.Name),
};
await foreach (var msg in playerX.SendAsync(receiver: playerO, chatHistory: conversationHistory, maxRound: 9))
{
conversationHistory.Add(msg);
// break if anyone wins
if (board.CheckWin(1))
{
Console.WriteLine("Player X wins!");
break;
}
else if (board.CheckWin(2))
{
Console.WriteLine("Player O wins!");
break;
}
// print the board
var displayBoard = await board.DisplayBoard();
Console.WriteLine(displayBoard);
}
// check if it's a draw
if (!board.CheckWin(1) && !board.CheckWin(2))
{
Console.WriteLine("It's a draw!");
}
public class NestMiddleware : IMiddleware
{
public NestMiddleware()
{
}
public string? Name => nameof(NestMiddleware);
public async Task<IMessage> InvokeAsync(MiddlewareContext context, IAgent agent, CancellationToken cancellationToken = default)
{
// check status
var checkStatusMessage = new TextMessage(Role.User, "check status");
var status = await agent.SendAsync(chatHistory: [checkStatusMessage]);
// get legal moves
var legalMoves = await agent.SendAsync("get legal moves", chatHistory: [checkStatusMessage, status]);
// make move
var move = await agent.SendAsync("make move", chatHistory: [status, legalMoves]);
return move;
}
}
public partial class TicTacToe
{
public int[,] board = new int[3, 3];
public TicTacToe(int[,] board)
{
if (board.GetLength(0) != 3 || board.GetLength(1) != 3)
{
throw new ArgumentException("The board should be 3x3.");
}
this.board = board;
}
/// <summary>
/// Get all legal moves on the board.
/// </summary>
[Function]
[KernelFunction]
[Description("Get all legal moves on the board.")]
public async Task<string> GetLegalMoves()
{
var legalMoves = new List<int[]>();
for (var i = 0; i < 3; i++)
{
for (var j = 0; j < 3; j++)
{
if (board[i, j] == 0)
{
legalMoves.Add([i, j]);
}
}
}
var sb = new StringBuilder();
sb.AppendLine("Legal moves:");
foreach (var move in legalMoves)
{
sb.AppendLine($"({move[0]}, {move[1]})");
}
return sb.ToString();
}
/// <summary>
/// Display the current board.
/// </summary>
[Function]
[KernelFunction]
[Description("Display the current board.")]
public Task<string> DisplayBoard()
{
var sb = new StringBuilder();
sb.AppendLine("Current board:");
var charMap = new Dictionary<int, string>
{
{ 0, "0" },
{ 1, "X" },
{ 2, "O" },
};
for (var i = 0; i < 3; i++)
{
sb.AppendLine(string.Join(" | ", charMap[board[i, 0]], charMap[board[i, 1]], charMap[board[i, 2]]));
}
return Task.FromResult(sb.ToString());
}
/// <summary>
/// Make a move on the board.
/// </summary>
/// <param name="player">The player making the move (1 for X, 2 for O).</param>
/// <param name="row">The row to make the move.Must be between 0 and 2.</param>
/// <param name="col">The column to make the move.Must be between 0 and 2.</param>
/// <exception cref="ArgumentException"></exception>
[Function]
[KernelFunction]
[Description("Make a move on the board.")]
public async Task<string> MakeMove(
[Description("The player making the move (1 for X, 2 for O).")]
int player,
[Description("The row to make the move. Must be between 0 and 2.")]
int row,
[Description("The column to make the move. Must be between 0 and 2.")]
int col)
{
if (board[row, col] != 0)
{
return $"Invalid move. The cell ({row}, {col}) is already occupied.";
}
if (player != 1 && player != 2)
{
return "Invalid player. Player must be 1 or 2.";
}
board[row, col] = player;
var sb = new StringBuilder();
sb.AppendLine($"Player {player} made a move at ({row}, {col}).");
return sb.ToString();
}
public bool CheckWin(int player)
{
// Check rows
for (var i = 0; i < 3; i++)
{
if (board[i, 0] == player && board[i, 1] == player && board[i, 2] == player)
{
return true;
}
}
// Check columns
for (var i = 0; i < 3; i++)
{
if (board[0, i] == player && board[1, i] == player && board[2, i] == player)
{
return true;
}
}
// Check diagonals
if (board[0, 0] == player && board[1, 1] == player && board[2, 2] == player)
{
return true;
}
if (board[0, 2] == player && board[1, 1] == player && board[2, 0] == player)
{
return true;
}
return false;
}
}