SpyBara
Go Premium

Documentation 2026-11-25 23:57 UTC to 2026-11-26 22:58 UTC

11 files changed +4,548 −28. View all changes and history on the product overview
2026
Thu 26 22:58 Wed 25 23:57 Tue 24 23:00 Mon 23 23:58 Sat 21 23:57 Fri 20 23:59 Thu 19 22:59 Wed 18 22:59 Tue 17 22:57 Mon 16 23:00 Fri 13 23:58 Thu 12 22:57 Wed 11 23:57 Tue 10 23:02 Mon 9 23:02 Sun 8 22:59 Sat 7 22:59 Fri 6 23:00 Thu 5 23:00 Wed 4 22:58 Tue 3 22:58 Mon 2 23:58 Sun 1 23:00
Details

186}186}

187```187```

188 188 

189```csharp

190using System;

191using System.Collections.Generic;

192using System.IO;

193using System.Text.Json;

194using System.Threading.Tasks;

195using Microsoft.ML.Tokenizers;

196 

197// This estimate uses cl100k_base and gpt-3.5-turbo-0613 message framing.

198// Other models, tools, and multimodal inputs need different accounting.

199static int CountChatMessageTokens(IReadOnlyList<Dictionary<string, string>> messages)

200{

201 ArgumentNullException.ThrowIfNull(messages);

202 TiktokenTokenizer encoding = TiktokenTokenizer.CreateForEncoding("cl100k_base");

203 int tokens = 3; // Final assistant reply overhead.

204 checked

205 {

206 foreach (Dictionary<string, string> message in messages)

207 {

208 tokens += 3; // Per-message framing.

209 foreach (KeyValuePair<string, string> field in message)

210 {

211 tokens += encoding.CountTokens(field.Value);

212 if (field.Key == "name")

213 {

214 tokens += 1;

215 }

216 }

217 }

218 }

219 return tokens;

220}

221 

222Dictionary<string, string>[] messages =

223[

224 new() { ["role"] = "user", ["content"] = "Hi" },

225];

226Console.WriteLine(CountChatMessageTokens(messages));

227```

228 

189```ruby229```ruby

190require "tiktoken_ruby"230require "tiktoken_ruby"

191 231 


398}438}

399```439```

400 440 

441```csharp

442using System;

443using System.Collections.Generic;

444using System.IO;

445using System.Text.Json;

446using System.Threading.Tasks;

447using Microsoft.ML.Tokenizers;

448 

449// This estimate uses cl100k_base and gpt-3.5-turbo-0613 message framing.

450// Other models, tools, and multimodal inputs need different accounting.

451static int CountChatMessageTokens(IReadOnlyList<Dictionary<string, string>> messages)

452{

453 ArgumentNullException.ThrowIfNull(messages);

454 TiktokenTokenizer encoding = TiktokenTokenizer.CreateForEncoding("cl100k_base");

455 int tokens = 3; // Final assistant reply overhead.

456 checked

457 {

458 foreach (Dictionary<string, string> message in messages)

459 {

460 tokens += 3; // Per-message framing.

461 foreach (KeyValuePair<string, string> field in message)

462 {

463 tokens += encoding.CountTokens(field.Value);

464 if (field.Key == "name")

465 {

466 tokens += 1;

467 }

468 }

469 }

470 }

471 return tokens;

472}

473 

474Dictionary<string, string>[] messages =

475[

476 new()

477 {

478 ["role"] = "system",

479 ["content"] = "You are a helpful, pattern-following assistant that translates corporate jargon into plain English.",

480 },

481 new()

482 {

483 ["role"] = "system",

484 ["name"] = "example_user",

485 ["content"] = "New synergies will help drive top-line growth.",

486 },

487 new()

488 {

489 ["role"] = "system",

490 ["name"] = "example_assistant",

491 ["content"] = "Things working well together will increase revenue.",

492 },

493 new()

494 {

495 ["role"] = "system",

496 ["name"] = "example_user",

497 ["content"] = "Let's circle back when we have more bandwidth to touch base on opportunities for increased leverage.",

498 },

499 new()

500 {

501 ["role"] = "system",

502 ["name"] = "example_assistant",

503 ["content"] = "Let's talk later when we're less busy about how to do better.",

504 },

505 new()

506 {

507 ["role"] = "user",

508 ["content"] = "This late pivot means we don't have time to boil the ocean for the client deliverable.",

509 },

510];

511int promptTokens = CountChatMessageTokens(messages);

512Console.WriteLine($"{promptTokens} prompt tokens counted.");

513```

514 

401```ruby515```ruby

402require "json"516require "json"

403 517 

Details

308}308}

309```309```

310 310 

311```csharp

312using System;

313using System.Collections.Generic;

314using System.ComponentModel;

315using System.Text.Json;

316using System.Threading.Tasks;

317using Microsoft.Extensions.DependencyInjection;

318using Microsoft.Extensions.Hosting;

319using Microsoft.Extensions.Logging;

320using ModelContextProtocol.Server;

321 

322HostApplicationBuilder builder = Host.CreateApplicationBuilder();

323// Stdout is reserved for MCP messages, including during host startup.

324builder.Logging.ClearProviders();

325builder.Logging.AddConsole(options => options.LogToStandardErrorThreshold = LogLevel.Trace);

326builder.Services

327 .AddMcpServer(options =>

328 {

329 options.ServerInfo = new() { Name = "customer-lookup", Version = "1.0.0" };

330 })

331 .WithStdioServerTransport()

332 .WithTools<CustomerLookupTools>();

333 

334using IHost host = builder.Build();

335await host.RunAsync();

336 

337[McpServerToolType]

338public sealed class CustomerLookupTools

339{

340 // Example data only; replace this collection with your customer data source.

341 private static readonly Dictionary<string, Customer> Customers =

342 new Dictionary<string, Customer>(StringComparer.Ordinal)

343 {

344 ["123"] = new("Example Customer", "pro"),

345 };

346 

347 // The parameter name is the public MCP schema key.

348#pragma warning disable CA1707

349 [McpServerTool(Name = "get_customer")]

350 [Description("Look up a customer in the example data.")]

351 public static string GetCustomer(

352 [Description("The customer ID to look up.")] string customer_id

353 )

354 {

355 ArgumentNullException.ThrowIfNull(customer_id);

356 Customers.TryGetValue(customer_id, out Customer? customer);

357 return JsonSerializer.Serialize(new { customer });

358 }

359 

360#pragma warning restore CA1707

361 

362 private sealed record Customer(

363 [property: System.Text.Json.Serialization.JsonPropertyName("name")] string Name,

364 [property: System.Text.Json.Serialization.JsonPropertyName("plan")] string Plan

365 );

366}

367```

368 

311```ruby369```ruby

312require "mcp"370require "mcp"

313require "json"371require "json"

Details

675System.out.println(vectors.get(0));675System.out.println(vectors.get(0));

676```676```

677 677 

678```csharp

679using System;

680using System.Collections.Generic;

681using System.IO;

682using System.Linq;

683using System.Text.Json;

684using System.Threading.Tasks;

685using Microsoft.VisualBasic.FileIO;

686 

687namespace OpenAI.Docs.Examples.Embeddings.LoadSavedEmbeddingsSample;

688 

689internal static class LoadSavedEmbeddings

690{

691 

692internal static List<double[]> LoadVectors()

693 {

694 // Use the CSV saved by the review-embedding example.

695 List<double[]> vectors = [];

696 foreach (Dictionary<string, string> row in ReadCsv("output/embedded_1k_reviews.csv", "ada_embedding"))

697 {

698 double[] vector = DecodeVector(row["ada_embedding"]);

699 if (vectors.Count > 0 && vector.Length != vectors[0].Length)

700 {

701 throw new InvalidDataException("Embedding dimensions differ.");

702 }

703 vectors.Add(vector);

704 }

705 if (vectors.Count == 0)

706 {

707 throw new InvalidDataException("The CSV contains no embeddings.");

708 }

709 

710 Console.WriteLine(JsonSerializer.Serialize(vectors[0]));

711 return vectors;

712 }

713 private static IEnumerable<Dictionary<string, string>> ReadCsv(string path, params string[] requiredColumns)

714 {

715 using TextFieldParser parser = new(path)

716 {

717 TextFieldType = FieldType.Delimited,

718 HasFieldsEnclosedInQuotes = true,

719 TrimWhiteSpace = false,

720 };

721 parser.SetDelimiters(",");

722 string[] headers = parser.ReadFields()

723 ?? throw new InvalidDataException("The CSV has no header.");

724 if (headers.Distinct(StringComparer.Ordinal).Count() != headers.Length

725 || requiredColumns.Any(column => !headers.Contains(column, StringComparer.Ordinal)))

726 {

727 throw new InvalidDataException("The CSV has duplicate headers or missing required columns.");

728 }

729 

730 while (!parser.EndOfData)

731 {

732 string[] fields = parser.ReadFields()

733 ?? throw new InvalidDataException("The CSV record is missing.");

734 if (fields.Length != headers.Length)

735 {

736 throw new InvalidDataException($"CSV record near line {parser.LineNumber} has the wrong field count.");

737 }

738 

739 Dictionary<string, string> row = new(StringComparer.Ordinal);

740 for (int i = 0; i < headers.Length; i++)

741 {

742 row.Add(headers[i], fields[i]);

743 }

744 yield return row;

745 }

746 }

747 

748 private static double[] DecodeVector(string json)

749 {

750 double[] vector = JsonSerializer.Deserialize<double[]>(json)

751 ?? throw new InvalidDataException("An embedding is null.");

752 if (vector.Length == 0 || vector.Any(value => !double.IsFinite(value)))

753 {

754 throw new InvalidDataException("Embeddings must contain finite numbers and at least one dimension.");

755 }

756 return vector;

757 }

758}

759```

760 

678```ruby761```ruby

679# standard:disable Lint/UselessAssignment -- Preserve named results for the next workflow step.762# standard:disable Lint/UselessAssignment -- Preserve named results for the next workflow step.

680require "csv"763require "csv"


2179javax.imageio.ImageIO.write(image, "png", Path.of("local-plot.png").toFile());2262javax.imageio.ImageIO.write(image, "png", Path.of("local-plot.png").toFile());

2180```2263```

2181 2264 

2265```csharp

2266using System;

2267using System.Collections.Generic;

2268using System.Globalization;

2269using System.IO;

2270using System.Linq;

2271using System.Text.Json;

2272using System.Threading.Tasks;

2273using Microsoft.VisualBasic.FileIO;

2274 

2275// The included illustrative CSV has been retaining Score, UserId and ProductId

2276// beside each corresponding ada_embedding. The basic embedding producer has

2277// been writing only combined and ada_embedding to a different output file.

2278// Real-data preparation has been preserving these review fields when attaching

2279// each generated vector; this example has been reading that labeled schema.

2280 

2281var (matrix, scores) = ReadReviews("data/illustrative-review-embeddings.csv");

2282// Exact t-SNE uses all pairwise affinities. Its quadratic cost is suitable

2283// for this 1,000-review tutorial, rather than very large datasets.

2284double[][] points = FitTsne(matrix, perplexity: 15, seed: 42, learningRate: 200);

2285 

2286WritePlot(points, scores, "local-plot.svg");

2287 

2288static double[][] FitTsne(double[][] matrix, double perplexity, int seed, double learningRate)

2289{

2290 int n = matrix.Length;

2291 if (perplexity < 1 || n <= perplexity || !double.IsFinite(perplexity) ||

2292 learningRate <= 0 || !double.IsFinite(learningRate))

2293 {

2294 throw new ArgumentException("Perplexity must be at least one and smaller than the row count; learning rate must be positive and finite.");

2295 }

2296 

2297 double[,] probabilities = JointProbabilities(matrix, perplexity);

2298 Random random = new(seed);

2299 double[][] points = Enumerable.Range(0, n).Select(_ => new[]

2300 {

2301 Gaussian(random) * 1e-4, Gaussian(random) * 1e-4,

2302 }).ToArray();

2303 double[,] velocity = new double[n, 2];

2304 double[,] gains = new double[n, 2];

2305 for (int i = 0; i < n; i++)

2306 {

2307 gains[i, 0] = gains[i, 1] = 1;

2308 }

2309 

2310 double[,] numerators = new double[n, n];

2311 double[,] gradient = new double[n, 2];

2312 for (int iteration = 0; iteration < 1000; iteration++)

2313 {

2314 Array.Clear(gradient);

2315 double normalization = 0;

2316 for (int i = 0; i < n; i++)

2317 {

2318 for (int j = i + 1; j < n; j++)

2319 {

2320 double dx = points[i][0] - points[j][0];

2321 double dy = points[i][1] - points[j][1];

2322 double numerator = 1 / (1 + dx * dx + dy * dy);

2323 numerators[i, j] = numerator;

2324 normalization += 2 * numerator;

2325 }

2326 }

2327 

2328 if (!double.IsFinite(normalization) || normalization <= 0)

2329 {

2330 throw new InvalidOperationException("The t-SNE affinity normalization is not finite and positive.");

2331 }

2332 

2333 // Student-t affinities and the exact gradient of KL(P || Q).

2334 // Early exaggeration and momentum follow the common t-SNE schedule.

2335 double exaggeration = iteration < 250 ? 12 : 1;

2336 for (int i = 0; i < n; i++)

2337 {

2338 for (int j = i + 1; j < n; j++)

2339 {

2340 double numerator = numerators[i, j];

2341 double q = numerator / normalization;

2342 double factor = 4 * (exaggeration * probabilities[i, j] - q) * numerator;

2343 for (int d = 0; d < 2; d++)

2344 {

2345 double contribution = factor * (points[i][d] - points[j][d]);

2346 gradient[i, d] += contribution;

2347 gradient[j, d] -= contribution;

2348 }

2349 }

2350 }

2351 

2352 double momentum = iteration < 250 ? 0.5 : 0.8;

2353 for (int i = 0; i < n; i++)

2354 {

2355 for (int d = 0; d < 2; d++)

2356 {

2357 gains[i, d] = Math.Sign(gradient[i, d]) != Math.Sign(velocity[i, d])

2358 ? gains[i, d] + 0.2 : Math.Max(0.01, gains[i, d] * 0.8);

2359 velocity[i, d] = momentum * velocity[i, d] - learningRate * gains[i, d] * gradient[i, d];

2360 points[i][d] += velocity[i, d];

2361 if (!double.IsFinite(points[i][d]))

2362 {

2363 throw new InvalidOperationException("The t-SNE optimization produced nonfinite coordinates.");

2364 }

2365 }

2366 }

2367 

2368 for (int d = 0; d < 2; d++)

2369 {

2370 double center = points.Average(point => point[d]);

2371 foreach (double[] point in points)

2372 {

2373 point[d] -= center;

2374 }

2375 }

2376 }

2377 

2378 return points;

2379}

2380 

2381// Binary-search a Gaussian precision per input vector until each conditional

2382// distribution has entropy log(perplexity), then symmetrize over both directions.

2383static double[,] JointProbabilities(double[][] matrix, double perplexity)

2384{

2385 int n = matrix.Length;

2386 double[,] conditional = new double[n, n];

2387 double targetEntropy = Math.Log(perplexity);

2388 for (int i = 0; i < n; i++)

2389 {

2390 double[] distances = new double[n];

2391 double minimum = double.PositiveInfinity;

2392 for (int j = 0; j < n; j++)

2393 {

2394 if (i == j)

2395 {

2396 continue;

2397 }

2398 

2399 double distance = 0;

2400 for (int d = 0; d < matrix[i].Length; d++)

2401 {

2402 double delta = matrix[i][d] - matrix[j][d];

2403 distance += delta * delta;

2404 }

2405 

2406 if (!double.IsFinite(distance))

2407 {

2408 throw new InvalidDataException("Embedding distances overflowed; rescale the input.");

2409 }

2410 

2411 distances[j] = distance;

2412 minimum = Math.Min(minimum, distance);

2413 }

2414 

2415 // Subtract the nearest distance before exponentiation to avoid

2416 // underflow of every affinity when the Gaussian is very narrow.

2417 double beta = 1, lower = 0, upper = double.PositiveInfinity;

2418 bool converged = false;

2419 for (int attempt = 0; attempt < 100; attempt++)

2420 {

2421 double total = 0;

2422 for (int j = 0; j < n; j++)

2423 {

2424 conditional[i, j] = i == j ? 0 : Math.Exp(-beta * (distances[j] - minimum));

2425 total += conditional[i, j];

2426 }

2427 

2428 double entropy = 0;

2429 for (int j = 0; j < n; j++)

2430 {

2431 conditional[i, j] /= total;

2432 double p = conditional[i, j];

2433 if (p > 0)

2434 {

2435 entropy -= p * Math.Log(p);

2436 }

2437 }

2438 

2439 double error = entropy - targetEntropy;

2440 if (Math.Abs(error) < 1e-5)

2441 {

2442 converged = true;

2443 break;

2444 }

2445 

2446 if (error > 0)

2447 {

2448 lower = beta;

2449 beta = double.IsPositiveInfinity(upper) ? beta * 2 : (beta + upper) / 2;

2450 }

2451 else

2452 {

2453 upper = beta;

2454 beta = (beta + lower) / 2;

2455 }

2456 }

2457 

2458 if (!converged)

2459 {

2460 throw new InvalidDataException("Cannot achieve perplexity 15 for these distances; inspect duplicate or degenerate embeddings.");

2461 }

2462 }

2463 

2464 double[,] joint = new double[n, n];

2465 for (int i = 0; i < n; i++)

2466 {

2467 for (int j = i + 1; j < n; j++)

2468 {

2469 joint[i, j] = joint[j, i] = (conditional[i, j] + conditional[j, i]) / (2 * n);

2470 }

2471 }

2472 

2473 return joint;

2474}

2475 

2476static double Gaussian(Random random)

2477{

2478 double radius = Math.Sqrt(-2 * Math.Log(1 - random.NextDouble()));

2479 return radius * Math.Cos(2 * Math.PI * random.NextDouble());

2480}

2481 

2482static void WritePlot(double[][] points, int[] scores, string path)

2483{

2484 // SVG keeps the plot portable across Linux, macOS, and Windows without

2485 // a platform-specific graphics package. Preserve labels in the artifact.

2486 System.Xml.Linq.XNamespace svg = "http://www.w3.org/2000/svg";

2487 System.Xml.Linq.XElement image = new(svg + "svg",

2488 new System.Xml.Linq.XAttribute("width", 640),

2489 new System.Xml.Linq.XAttribute("height", 480),

2490 new System.Xml.Linq.XAttribute("viewBox", "0 0 640 480"),

2491 new System.Xml.Linq.XElement(svg + "title", "Review embeddings colored by score"),

2492 new System.Xml.Linq.XElement(svg + "rect",

2493 new System.Xml.Linq.XAttribute("width", 640),

2494 new System.Xml.Linq.XAttribute("height", 480),

2495 new System.Xml.Linq.XAttribute("fill", "white")));

2496 string[] palette = ["#e41a1c", "#ff7f00", "#d4af00", "#00a6ca", "#238b45"];

2497 double minX = points.Min(point => point[0]), maxX = points.Max(point => point[0]);

2498 double minY = points.Min(point => point[1]), maxY = points.Max(point => point[1]);

2499 for (int i = 0; i < points.Length; i++)

2500 {

2501 double x = 20 + 600 * (points[i][0] - minX) / Math.Max(1e-12, maxX - minX);

2502 double y = 440 - 400 * (points[i][1] - minY) / Math.Max(1e-12, maxY - minY);

2503 image.Add(new System.Xml.Linq.XElement(svg + "circle",

2504 new System.Xml.Linq.XAttribute("cx", x.ToString("R", CultureInfo.InvariantCulture)),

2505 new System.Xml.Linq.XAttribute("cy", y.ToString("R", CultureInfo.InvariantCulture)),

2506 new System.Xml.Linq.XAttribute("r", 3),

2507 new System.Xml.Linq.XAttribute("fill", palette[scores[i] - 1]),

2508 new System.Xml.Linq.XAttribute("data-score", scores[i]),

2509 new System.Xml.Linq.XAttribute("data-review", i)));

2510 }

2511 

2512 for (int rating = 1; rating <= 5; rating++)

2513 {

2514 image.Add(new System.Xml.Linq.XElement(svg + "text",

2515 new System.Xml.Linq.XAttribute("x", 20 + (rating - 1) * 120),

2516 new System.Xml.Linq.XAttribute("y", 470),

2517 new System.Xml.Linq.XAttribute("fill", palette[rating - 1]),

2518 new System.Xml.Linq.XAttribute("font-size", 14),

2519 $"Score {rating}"));

2520 }

2521 

2522 new System.Xml.Linq.XDocument(image).Save(path);

2523}

2524 

2525// Read the CSV produced by the review-embedding workflow. TextFieldParser

2526// handles quoted JSON vectors, commas, escaped quotes, and multiline reviews.

2527static (double[][] Vectors, int[] Scores) ReadReviews(string path)

2528{

2529 using TextFieldParser csv = new(path);

2530 csv.TextFieldType = FieldType.Delimited;

2531 csv.SetDelimiters(",");

2532 csv.HasFieldsEnclosedInQuotes = true;

2533 string[] header = csv.ReadFields() ?? throw new InvalidDataException("The CSV is empty.");

2534 int embeddingColumn = Array.IndexOf(header, "ada_embedding");

2535 int scoreColumn = Array.IndexOf(header, "Score");

2536 if (embeddingColumn < 0 || scoreColumn < 0)

2537 {

2538 throw new InvalidDataException("Expected ada_embedding and Score columns.");

2539 }

2540 

2541 List<double[]> vectors = [];

2542 List<int> scores = [];

2543 while (!csv.EndOfData)

2544 {

2545 string[] row = csv.ReadFields() ?? throw new InvalidDataException("Missing CSV row.");

2546 if (row.Length != header.Length)

2547 {

2548 throw new InvalidDataException("The CSV row does not match its header.");

2549 }

2550 

2551 double[] vector = JsonSerializer.Deserialize<double[]>(row[embeddingColumn])

2552 ?? throw new InvalidDataException("A review has no embedding.");

2553 if (vector.Length == 0 || vector.Any(value => !double.IsFinite(value)) ||

2554 (vectors.Count > 0 && vector.Length != vectors[0].Length))

2555 {

2556 throw new InvalidDataException("Embeddings must be finite vectors of equal nonzero length.");

2557 }

2558 

2559 int score = int.Parse(row[scoreColumn], CultureInfo.InvariantCulture);

2560 if (score is < 1 or > 5)

2561 {

2562 throw new InvalidDataException("Review scores must be integers from 1 through 5.");

2563 }

2564 

2565 vectors.Add(vector);

2566 scores.Add(score);

2567 }

2568 

2569 if (vectors.Count == 0)

2570 {

2571 throw new InvalidDataException("The CSV has no reviews.");

2572 }

2573 

2574 return (vectors.ToArray(), scores.ToArray());

2575}

2576```

2577 

2182```ruby2578```ruby

2183require "csv"2579require "csv"

2184require "json"2580require "json"


2434 2830 

2435```2831```

2436 2832 

2833```csharp

2834using System;

2835using System.Collections.Generic;

2836using System.Globalization;

2837using System.IO;

2838using System.Linq;

2839using System.Text.Json;

2840using System.Threading.Tasks;

2841using Microsoft.VisualBasic.FileIO;

2842 

2843var (yTrain, yTest, xTrain, xTest) = SplitDataset();

2844 

2845// The included illustrative CSV has been retaining Score, UserId and ProductId

2846// beside each corresponding ada_embedding. The basic embedding producer has

2847// been writing only combined and ada_embedding to a different output file.

2848// Real-data preparation has been preserving these review fields when attaching

2849// each generated vector; this example has been reading that labeled schema.

2850static (int[] Train, int[] Test, double[][] TrainVectors, double[][] TestVectors) SplitDataset()

2851{

2852 List<double[]> vectors = [];

2853 List<int> scores = [];

2854 foreach (Dictionary<string, string> row in ReadCsv(

2855 "data/illustrative-review-embeddings.csv", "ada_embedding", "Score"))

2856 {

2857 double[] vector = DecodeVector(row["ada_embedding"]);

2858 if (vectors.Count > 0 && vector.Length != vectors[0].Length)

2859 {

2860 throw new InvalidDataException("Embedding dimensions differ.");

2861 }

2862 int score = int.Parse(row["Score"], NumberStyles.Integer, CultureInfo.InvariantCulture);

2863 vectors.Add(vector);

2864 scores.Add(score);

2865 }

2866 if (vectors.Count < 2)

2867 {

2868 throw new InvalidDataException("Splitting requires at least two reviews.");

2869 }

2870 

2871 // Shuffle row indices once to preserve vector/score alignment.

2872 // Seed 42 is repeatable in this .NET runtime, not identical to Python's permutation.

2873 int[] indices = Enumerable.Range(0, vectors.Count).ToArray();

2874 Random random = new(42);

2875 for (int i = indices.Length - 1; i > 0; i--)

2876 {

2877 int j = random.Next(i + 1);

2878 (indices[i], indices[j]) = (indices[j], indices[i]);

2879 }

2880 int testSize = (int)Math.Ceiling(vectors.Count * 0.2);

2881 int[] testIndices = indices[..testSize];

2882 int[] trainIndices = indices[testSize..];

2883 double[][] xTrain = trainIndices.Select(index => vectors[index]).ToArray();

2884 double[][] xTest = testIndices.Select(index => vectors[index]).ToArray();

2885 int[] yTrain = trainIndices.Select(index => scores[index]).ToArray();

2886 int[] yTest = testIndices.Select(index => scores[index]).ToArray();

2887 Console.WriteLine($"Training examples: {xTrain.Length}");

2888 Console.WriteLine($"Test examples: {xTest.Length}");

2889 return (yTrain, yTest, xTrain, xTest);

2890}

2891static IEnumerable<Dictionary<string, string>> ReadCsv(string path, params string[] requiredColumns)

2892{

2893 using TextFieldParser parser = new(path)

2894 {

2895 TextFieldType = FieldType.Delimited,

2896 HasFieldsEnclosedInQuotes = true,

2897 TrimWhiteSpace = false,

2898 };

2899 parser.SetDelimiters(",");

2900 string[] headers = parser.ReadFields()

2901 ?? throw new InvalidDataException("The CSV has no header.");

2902 if (headers.Distinct(StringComparer.Ordinal).Count() != headers.Length

2903 || requiredColumns.Any(column => !headers.Contains(column, StringComparer.Ordinal)))

2904 {

2905 throw new InvalidDataException("The CSV has duplicate headers or missing required columns.");

2906 }

2907 

2908 while (!parser.EndOfData)

2909 {

2910 string[] fields = parser.ReadFields()

2911 ?? throw new InvalidDataException("The CSV record is missing.");

2912 if (fields.Length != headers.Length)

2913 {

2914 throw new InvalidDataException($"CSV record near line {parser.LineNumber} has the wrong field count.");

2915 }

2916 

2917 Dictionary<string, string> row = new(StringComparer.Ordinal);

2918 for (int i = 0; i < headers.Length; i++)

2919 {

2920 row.Add(headers[i], fields[i]);

2921 }

2922 yield return row;

2923 }

2924}

2925 

2926static double[] DecodeVector(string json)

2927{

2928 double[] vector = JsonSerializer.Deserialize<double[]>(json)

2929 ?? throw new InvalidDataException("An embedding is null.");

2930 if (vector.Length == 0 || vector.Any(value => !double.IsFinite(value)))

2931 {

2932 throw new InvalidDataException("Embeddings must contain finite numbers and at least one dimension.");

2933 }

2934 return vector;

2935}

2936```

2937 

2437```ruby2938```ruby

2438vectors = rows.map { |row| row.fetch("ada_embedding") }2939vectors = rows.map { |row| row.fetch("ada_embedding") }

2439scores = rows.map { |row| Integer(row.fetch("Score")) }2940scores = rows.map { |row| Integer(row.fetch("Score")) }


2685System.out.println(predictions);3186System.out.println(predictions);

2686```3187```

2687 3188 

3189```csharp

3190using System;

3191using System.Collections.Generic;

3192using System.Globalization;

3193using System.IO;

3194using System.Linq;

3195using System.Text.Json;

3196using System.Threading.Tasks;

3197using Microsoft.VisualBasic.FileIO;

3198 

3199// The included illustrative CSV has been retaining Score, UserId and ProductId

3200// beside each corresponding ada_embedding. The basic embedding producer has

3201// been writing only combined and ada_embedding to a different output file.

3202// Real-data preparation has been preserving these review fields when attaching

3203// each generated vector; this example has been reading that labeled schema.

3204 

3205var (vectors, scores) = ReadReviews("data/illustrative-review-embeddings.csv");

3206var (trainIndices, testIndices) = Split(vectors.Length, testFraction: 0.2, seed: 42);

3207double[][] xTrain = trainIndices.Select(i => vectors[i]).ToArray();

3208int[] yTrain = trainIndices.Select(i => scores[i]).ToArray();

3209double[][] xTest = testIndices.Select(i => vectors[i]).ToArray();

3210int[] yTest = testIndices.Select(i => scores[i]).ToArray();

3211Node[] forest = FitForest(xTrain, yTrain);

3212double[] predictions = Predict(forest, xTest);

3213double meanSquaredError = predictions.Zip(yTest)

3214 .Average(pair => Math.Pow(pair.First - pair.Second, 2));

3215Console.WriteLine(JsonSerializer.Serialize(predictions));

3216 

3217static Node[] FitForest(double[][] xTrain, int[] yTrain)

3218{

3219 Random random = new(42);

3220 return Enumerable.Range(0, 100).Select(treeIndex =>

3221 {

3222 int[] bootstrap = Enumerable.Range(0, xTrain.Length)

3223 .Select(rowIndex => random.Next(xTrain.Length)).ToArray();

3224 return GrowTree(xTrain, yTrain, bootstrap, random);

3225 }).ToArray();

3226}

3227 

3228static double[] Predict(Node[] forest, double[][] vectors) =>

3229 vectors.Select(row => forest.Average(tree => Leaf(tree, row).Value)).ToArray();

3230 

3231 

3232static Node Leaf(Node tree, double[] row)

3233{

3234 while (tree.Feature >= 0)

3235 {

3236 tree = row[tree.Feature] <= tree.Threshold ? tree.Left! : tree.Right!;

3237 }

3238 

3239 return tree;

3240}

3241 

3242// Bootstrap CART trees: search exact thresholds between distinct feature

3243// values. The split criterion is the sum of squared residuals.

3244static Node GrowTree(double[][] x, int[] y, int[] rows, Random random)

3245{

3246 double mean = rows.Average(row => (double)y[row]);

3247 if (rows.Length < 2 || rows.All(row => y[row] == y[rows[0]]))

3248 {

3249 return new Node { Value = mean };

3250 }

3251 

3252 int[] features = Enumerable.Range(0, x[0].Length).ToArray();

3253 random.Shuffle(features);

3254 int featureCount = features.Length;

3255 int bestFeature = -1;

3256 double bestThreshold = 0;

3257 double bestLoss = double.PositiveInfinity;

3258 // If all randomly selected features are constant, inspect further

3259 // features until at least one valid partition has been found.

3260 for (int f = 0; f < features.Length && (f < featureCount || bestFeature < 0); f++)

3261 {

3262 int feature = features[f];

3263 int[] ordered = rows.OrderBy(row => x[row][feature]).ToArray();

3264 double leftSum = 0, leftSquaredSum = 0;

3265 double rightSum = rows.Sum(row => (double)y[row]);

3266 double rightSquaredSum = rows.Sum(row => (double)y[row] * y[row]);

3267 for (int split = 1; split < ordered.Length; split++)

3268 {

3269 int score = y[ordered[split - 1]];

3270 leftSum += score;

3271 rightSum -= score;

3272 leftSquaredSum += score * score;

3273 rightSquaredSum -= score * score;

3274 double lower = x[ordered[split - 1]][feature];

3275 double upper = x[ordered[split]][feature];

3276 if (lower == upper)

3277 {

3278 continue;

3279 }

3280 

3281 int rightCount = ordered.Length - split;

3282 double loss = leftSquaredSum - leftSum * leftSum / split

3283 + rightSquaredSum - rightSum * rightSum / rightCount;

3284 if (loss < bestLoss)

3285 {

3286 bestLoss = loss;

3287 bestFeature = feature;

3288 // A rounded midpoint must remain strictly below upper.

3289 bestThreshold = lower / 2 + upper / 2;

3290 if (bestThreshold >= upper)

3291 {

3292 bestThreshold = lower;

3293 }

3294 }

3295 }

3296 }

3297 

3298 if (bestFeature < 0)

3299 {

3300 return new Node { Value = mean };

3301 }

3302 

3303 int[] left = rows.Where(row => x[row][bestFeature] <= bestThreshold).ToArray();

3304 int[] right = rows.Where(row => x[row][bestFeature] > bestThreshold).ToArray();

3305 return new Node

3306 {

3307 Feature = bestFeature,

3308 Threshold = bestThreshold,

3309 Left = GrowTree(x, y, left, random),

3310 Right = GrowTree(x, y, right, random),

3311 };

3312}

3313 

3314static (int[] Train, int[] Test) Split(int count, double testFraction, int seed)

3315{

3316 int testCount = (int)Math.Ceiling(count * testFraction);

3317 if (testCount < 1 || testCount >= count)

3318 {

3319 throw new ArgumentException("Provide enough reviews for nonempty training and test sets.", nameof(count));

3320 }

3321 

3322 int[] indices = Enumerable.Range(0, count).ToArray();

3323 Random random = new(seed);

3324 random.Shuffle(indices);

3325 return (indices[testCount..], indices[..testCount]);

3326}

3327 

3328// Read the CSV produced by the review-embedding workflow. TextFieldParser

3329// handles quoted JSON vectors, commas, escaped quotes, and multiline reviews.

3330static (double[][] Vectors, int[] Scores) ReadReviews(string path)

3331{

3332 using TextFieldParser csv = new(path);

3333 csv.TextFieldType = FieldType.Delimited;

3334 csv.SetDelimiters(",");

3335 csv.HasFieldsEnclosedInQuotes = true;

3336 string[] header = csv.ReadFields() ?? throw new InvalidDataException("The CSV is empty.");

3337 int embeddingColumn = Array.IndexOf(header, "ada_embedding");

3338 int scoreColumn = Array.IndexOf(header, "Score");

3339 if (embeddingColumn < 0 || scoreColumn < 0)

3340 {

3341 throw new InvalidDataException("Expected ada_embedding and Score columns.");

3342 }

3343 

3344 List<double[]> vectors = [];

3345 List<int> scores = [];

3346 while (!csv.EndOfData)

3347 {

3348 string[] row = csv.ReadFields() ?? throw new InvalidDataException("Missing CSV row.");

3349 if (row.Length != header.Length)

3350 {

3351 throw new InvalidDataException("The CSV row does not match its header.");

3352 }

3353 

3354 double[] vector = JsonSerializer.Deserialize<double[]>(row[embeddingColumn])

3355 ?? throw new InvalidDataException("A review has no embedding.");

3356 if (vector.Length == 0 || vector.Any(value => !double.IsFinite(value)) ||

3357 (vectors.Count > 0 && vector.Length != vectors[0].Length))

3358 {

3359 throw new InvalidDataException("Embeddings must be finite vectors of equal nonzero length.");

3360 }

3361 

3362 int score = int.Parse(row[scoreColumn], CultureInfo.InvariantCulture);

3363 if (score is < 1 or > 5)

3364 {

3365 throw new InvalidDataException("Review scores must be integers from 1 through 5.");

3366 }

3367 

3368 vectors.Add(vector);

3369 scores.Add(score);

3370 }

3371 

3372 if (vectors.Count == 0)

3373 {

3374 throw new InvalidDataException("The CSV has no reviews.");

3375 }

3376 

3377 return (vectors.ToArray(), scores.ToArray());

3378}

3379 

3380sealed class Node

3381{

3382 internal int Feature { get; init; } = -1;

3383 internal double Threshold { get; init; }

3384 internal double Value { get; init; }

3385 internal Node? Left { get; init; }

3386 internal Node? Right { get; init; }

3387}

3388```

3389 

2688```ruby3390```ruby

2689require "rumale/ensemble"3391require "rumale/ensemble"

2690 3392 


2965System.out.println(predictions);3667System.out.println(predictions);

2966```3668```

2967 3669 

3670```csharp

3671using System;

3672using System.Collections.Generic;

3673using System.Globalization;

3674using System.IO;

3675using System.Linq;

3676using System.Text.Json;

3677using System.Threading.Tasks;

3678using Microsoft.VisualBasic.FileIO;

3679 

3680// The included illustrative CSV has been retaining Score, UserId and ProductId

3681// beside each corresponding ada_embedding. The basic embedding producer has

3682// been writing only combined and ada_embedding to a different output file.

3683// Real-data preparation has been preserving these review fields when attaching

3684// each generated vector; this example has been reading that labeled schema.

3685 

3686var (vectors, scores) = ReadReviews("data/illustrative-review-embeddings.csv");

3687var (trainIndices, testIndices) = Split(vectors.Length, testFraction: 0.2, seed: 42);

3688double[][] xTrain = trainIndices.Select(i => vectors[i]).ToArray();

3689int[] yTrain = trainIndices.Select(i => scores[i]).ToArray();

3690double[][] xTest = testIndices.Select(i => vectors[i]).ToArray();

3691int[] yTest = testIndices.Select(i => scores[i]).ToArray();

3692Node[] forest = FitForest(xTrain, yTrain);

3693int[] classes = yTrain.Distinct().Order().ToArray();

3694int[] predictions = Predict(forest, xTest, classes);

3695double accuracy = predictions.Zip(yTest).Count(pair => pair.First == pair.Second) / (double)yTest.Length;

3696Console.WriteLine(JsonSerializer.Serialize(predictions));

3697 

3698static Node[] FitForest(double[][] xTrain, int[] yTrain)

3699{

3700 Random random = new(42);

3701 return Enumerable.Range(0, 100).Select(treeIndex =>

3702 {

3703 int[] bootstrap = Enumerable.Range(0, xTrain.Length)

3704 .Select(rowIndex => random.Next(xTrain.Length)).ToArray();

3705 return GrowTree(xTrain, yTrain, bootstrap, random);

3706 }).ToArray();

3707}

3708 

3709// Average the fitted multiclass leaf probabilities, then choose the largest.

3710static int[] Predict(Node[] forest, double[][] vectors, int[] classes) =>

3711 vectors.Select(row => classes.MaxBy(label =>

3712 forest.Sum(tree => Leaf(tree, row).Probabilities[label - 1]))).ToArray();

3713 

3714 

3715static Node Leaf(Node tree, double[] row)

3716{

3717 while (tree.Feature >= 0)

3718 {

3719 tree = row[tree.Feature] <= tree.Threshold ? tree.Left! : tree.Right!;

3720 }

3721 

3722 return tree;

3723}

3724 

3725// Bootstrap CART trees: search exact thresholds between distinct feature

3726// values. The split criterion is weighted multiclass Gini impurity.

3727static Node GrowTree(double[][] x, int[] y, int[] rows, Random random)

3728{

3729 double[] counts = new double[5];

3730 foreach (int row in rows)

3731 {

3732 counts[y[row] - 1]++;

3733 }

3734 

3735 if (rows.Length < 2 || rows.All(row => y[row] == y[rows[0]]))

3736 {

3737 return new Node { Probabilities = counts.Select(count => count / rows.Length).ToArray() };

3738 }

3739 

3740 int[] features = Enumerable.Range(0, x[0].Length).ToArray();

3741 random.Shuffle(features);

3742 int featureCount = Math.Max(1, (int)Math.Sqrt(features.Length));

3743 int bestFeature = -1;

3744 double bestThreshold = 0;

3745 double bestLoss = double.PositiveInfinity;

3746 // If all randomly selected features are constant, inspect further

3747 // features until at least one valid partition has been found.

3748 for (int f = 0; f < features.Length && (f < featureCount || bestFeature < 0); f++)

3749 {

3750 int feature = features[f];

3751 int[] ordered = rows.OrderBy(row => x[row][feature]).ToArray();

3752 double[] leftCounts = new double[5];

3753 double[] rightCounts = (double[])counts.Clone();

3754 for (int split = 1; split < ordered.Length; split++)

3755 {

3756 int score = y[ordered[split - 1]];

3757 leftCounts[score - 1]++;

3758 rightCounts[score - 1]--;

3759 double lower = x[ordered[split - 1]][feature];

3760 double upper = x[ordered[split]][feature];

3761 if (lower == upper)

3762 {

3763 continue;

3764 }

3765 

3766 int rightCount = ordered.Length - split;

3767 double loss = split - leftCounts.Sum(count => count * count) / split

3768 + rightCount - rightCounts.Sum(count => count * count) / rightCount;

3769 if (loss < bestLoss)

3770 {

3771 bestLoss = loss;

3772 bestFeature = feature;

3773 // A rounded midpoint must remain strictly below upper.

3774 bestThreshold = lower / 2 + upper / 2;

3775 if (bestThreshold >= upper)

3776 {

3777 bestThreshold = lower;

3778 }

3779 }

3780 }

3781 }

3782 

3783 if (bestFeature < 0)

3784 {

3785 return new Node { Probabilities = counts.Select(count => count / rows.Length).ToArray() };

3786 }

3787 

3788 int[] left = rows.Where(row => x[row][bestFeature] <= bestThreshold).ToArray();

3789 int[] right = rows.Where(row => x[row][bestFeature] > bestThreshold).ToArray();

3790 return new Node

3791 {

3792 Feature = bestFeature,

3793 Threshold = bestThreshold,

3794 Left = GrowTree(x, y, left, random),

3795 Right = GrowTree(x, y, right, random),

3796 };

3797}

3798 

3799static (int[] Train, int[] Test) Split(int count, double testFraction, int seed)

3800{

3801 int testCount = (int)Math.Ceiling(count * testFraction);

3802 if (testCount < 1 || testCount >= count)

3803 {

3804 throw new ArgumentException("Provide enough reviews for nonempty training and test sets.", nameof(count));

3805 }

3806 

3807 int[] indices = Enumerable.Range(0, count).ToArray();

3808 Random random = new(seed);

3809 random.Shuffle(indices);

3810 return (indices[testCount..], indices[..testCount]);

3811}

3812 

3813// Read the CSV produced by the review-embedding workflow. TextFieldParser

3814// handles quoted JSON vectors, commas, escaped quotes, and multiline reviews.

3815static (double[][] Vectors, int[] Scores) ReadReviews(string path)

3816{

3817 using TextFieldParser csv = new(path);

3818 csv.TextFieldType = FieldType.Delimited;

3819 csv.SetDelimiters(",");

3820 csv.HasFieldsEnclosedInQuotes = true;

3821 string[] header = csv.ReadFields() ?? throw new InvalidDataException("The CSV is empty.");

3822 int embeddingColumn = Array.IndexOf(header, "ada_embedding");

3823 int scoreColumn = Array.IndexOf(header, "Score");

3824 if (embeddingColumn < 0 || scoreColumn < 0)

3825 {

3826 throw new InvalidDataException("Expected ada_embedding and Score columns.");

3827 }

3828 

3829 List<double[]> vectors = [];

3830 List<int> scores = [];

3831 while (!csv.EndOfData)

3832 {

3833 string[] row = csv.ReadFields() ?? throw new InvalidDataException("Missing CSV row.");

3834 if (row.Length != header.Length)

3835 {

3836 throw new InvalidDataException("The CSV row does not match its header.");

3837 }

3838 

3839 double[] vector = JsonSerializer.Deserialize<double[]>(row[embeddingColumn])

3840 ?? throw new InvalidDataException("A review has no embedding.");

3841 if (vector.Length == 0 || vector.Any(value => !double.IsFinite(value)) ||

3842 (vectors.Count > 0 && vector.Length != vectors[0].Length))

3843 {

3844 throw new InvalidDataException("Embeddings must be finite vectors of equal nonzero length.");

3845 }

3846 

3847 int score = int.Parse(row[scoreColumn], CultureInfo.InvariantCulture);

3848 if (score is < 1 or > 5)

3849 {

3850 throw new InvalidDataException("Review scores must be integers from 1 through 5.");

3851 }

3852 

3853 vectors.Add(vector);

3854 scores.Add(score);

3855 }

3856 

3857 if (vectors.Count == 0)

3858 {

3859 throw new InvalidDataException("The CSV has no reviews.");

3860 }

3861 

3862 return (vectors.ToArray(), scores.ToArray());

3863}

3864 

3865sealed class Node

3866{

3867 internal int Feature { get; init; } = -1;

3868 internal double Threshold { get; init; }

3869 internal double[] Probabilities { get; init; } = new double[5];

3870 internal Node? Left { get; init; }

3871 internal Node? Right { get; init; }

3872}

3873```

3874 

2968```ruby3875```ruby

2969require "rumale/ensemble"3876require "rumale/ensemble"

2970 3877 


3433}4340}

3434```4341```

3435 4342 

4343```csharp

4344using System;

4345using System.Collections.Generic;

4346using System.IO;

4347using System.Linq;

4348using System.Text.Json;

4349using System.Threading.Tasks;

4350using Microsoft.VisualBasic.FileIO;

4351 

4352namespace OpenAI.Docs.Examples.Embeddings.AverageUserAndProductEmbeddingsSample;

4353 

4354internal static class AverageUserAndProductEmbeddings

4355{

4356 

4357// The included illustrative CSV has been retaining Score, UserId and ProductId

4358 // beside each corresponding ada_embedding. The basic embedding producer has

4359 // been writing only combined and ada_embedding to a different output file.

4360 // Real-data preparation has been preserving these review fields when attaching

4361 // each generated vector; this example has been reading that labeled schema.

4362 internal static (Dictionary<string, double[]> Users, Dictionary<string, double[]> Products) AverageReviews()

4363 {

4364 // Preserve the user and product columns alongside each saved review vector.

4365 List<Review> reviews = [];

4366 foreach (Dictionary<string, string> row in ReadCsv(

4367 "data/illustrative-review-embeddings.csv", "UserId", "ProductId", "ada_embedding"))

4368 {

4369 if (string.IsNullOrWhiteSpace(row["UserId"]) || string.IsNullOrWhiteSpace(row["ProductId"]))

4370 {

4371 throw new InvalidDataException("Each review needs a user ID and product ID.");

4372 }

4373 reviews.Add(new Review(row["UserId"], row["ProductId"], DecodeVector(row["ada_embedding"])));

4374 }

4375 if (reviews.Count == 0)

4376 {

4377 throw new InvalidDataException("The CSV contains no reviews.");

4378 }

4379 

4380 Dictionary<string, double[]> users = AverageBy(reviews, review => review.UserId);

4381 Dictionary<string, double[]> products = AverageBy(reviews, review => review.ProductId);

4382 Console.WriteLine(JsonSerializer.Serialize(users));

4383 Console.WriteLine(JsonSerializer.Serialize(products));

4384 return (users, products);

4385 }

4386 internal sealed record Review(string UserId, string ProductId, double[] Vector);

4387 

4388 internal static Dictionary<string, double[]> AverageBy(

4389 List<Review> reviews, Func<Review, string> groupKey)

4390 {

4391 int dimensions = reviews[0].Vector.Length;

4392 Dictionary<string, double[]> means = new(StringComparer.Ordinal);

4393 foreach (IGrouping<string, Review> group in reviews.GroupBy(groupKey, StringComparer.Ordinal))

4394 {

4395 double[] mean = new double[dimensions];

4396 int count = 0;

4397 foreach (Review review in group)

4398 {

4399 if (review.Vector.Length != dimensions)

4400 {

4401 throw new InvalidDataException("Embedding dimensions differ.");

4402 }

4403 count++;

4404 for (int dimension = 0; dimension < dimensions; dimension++)

4405 {

4406 mean[dimension] += review.Vector[dimension];

4407 if (!double.IsFinite(mean[dimension]))

4408 {

4409 throw new InvalidDataException("The grouped sum exceeds the numeric range.");

4410 }

4411 }

4412 }

4413 for (int dimension = 0; dimension < dimensions; dimension++)

4414 {

4415 mean[dimension] /= count;

4416 }

4417 means.Add(group.Key, mean);

4418 }

4419 return means;

4420 }

4421 

4422 private static IEnumerable<Dictionary<string, string>> ReadCsv(string path, params string[] requiredColumns)

4423 {

4424 using TextFieldParser parser = new(path)

4425 {

4426 TextFieldType = FieldType.Delimited,

4427 HasFieldsEnclosedInQuotes = true,

4428 TrimWhiteSpace = false,

4429 };

4430 parser.SetDelimiters(",");

4431 string[] headers = parser.ReadFields()

4432 ?? throw new InvalidDataException("The CSV has no header.");

4433 if (headers.Distinct(StringComparer.Ordinal).Count() != headers.Length

4434 || requiredColumns.Any(column => !headers.Contains(column, StringComparer.Ordinal)))

4435 {

4436 throw new InvalidDataException("The CSV has duplicate headers or missing required columns.");

4437 }

4438 

4439 while (!parser.EndOfData)

4440 {

4441 string[] fields = parser.ReadFields()

4442 ?? throw new InvalidDataException("The CSV record is missing.");

4443 if (fields.Length != headers.Length)

4444 {

4445 throw new InvalidDataException($"CSV record near line {parser.LineNumber} has the wrong field count.");

4446 }

4447 

4448 Dictionary<string, string> row = new(StringComparer.Ordinal);

4449 for (int i = 0; i < headers.Length; i++)

4450 {

4451 row.Add(headers[i], fields[i]);

4452 }

4453 yield return row;

4454 }

4455 }

4456 

4457 private static double[] DecodeVector(string json)

4458 {

4459 double[] vector = JsonSerializer.Deserialize<double[]>(json)

4460 ?? throw new InvalidDataException("An embedding is null.");

4461 if (vector.Length == 0 || vector.Any(value => !double.IsFinite(value)))

4462 {

4463 throw new InvalidDataException("Embeddings must contain finite numbers and at least one dimension.");

4464 }

4465 return vector;

4466 }

4467}

4468```

4469 

3436```ruby4470```ruby

3437vectors = rows.map { |row| row.fetch("ada_embedding") }4471vectors = rows.map { |row| row.fetch("ada_embedding") }

3438user_ids = rows.map { |row| row.fetch("UserId") }4472user_ids = rows.map { |row| row.fetch("UserId") }


3725System.out.println(Arrays.toString(clusters.y));4759System.out.println(Arrays.toString(clusters.y));

3726```4760```

3727 4761 

4762```csharp

4763using System;

4764using System.Collections.Generic;

4765using System.Globalization;

4766using System.IO;

4767using System.Linq;

4768using System.Text.Json;

4769using System.Threading.Tasks;

4770using Microsoft.VisualBasic.FileIO;

4771 

4772// The included illustrative CSV has been retaining Score, UserId and ProductId

4773// beside each corresponding ada_embedding. The basic embedding producer has

4774// been writing only combined and ada_embedding to a different output file.

4775// Real-data preparation has been preserving these review fields when attaching

4776// each generated vector; this example has been reading that labeled schema.

4777 

4778var (matrix, _) = ReadReviews("data/illustrative-review-embeddings.csv");

4779var (labels, centers) = FitKMeans(matrix, clusterCount: 4, seed: 42);

4780Console.WriteLine(JsonSerializer.Serialize(labels));

4781 

4782// K-means++ initialization followed by Lloyd's algorithm, with squared

4783// Euclidean distance and explicit recovery of empty clusters.

4784static (int[] Labels, double[][] Centers) FitKMeans(

4785 double[][] matrix, int clusterCount, int seed)

4786{

4787 if (matrix.Length < clusterCount || clusterCount < 1)

4788 {

4789 throw new ArgumentException("Provide at least one row per cluster.", nameof(matrix));

4790 }

4791 

4792 Random random = new(seed);

4793 List<double[]> centers = [(double[])matrix[random.Next(matrix.Length)].Clone()];

4794 while (centers.Count < clusterCount)

4795 {

4796 double[] distances = matrix.Select(row => centers.Min(center => SquaredDistance(row, center))).ToArray();

4797 double total = distances.Sum();

4798 if (!double.IsFinite(total) || total <= 0)

4799 {

4800 throw new ArgumentException("Provide at least four distinct, bounded embeddings.", nameof(matrix));

4801 }

4802 

4803 double target = random.NextDouble() * total;

4804 int chosen = 0;

4805 while (chosen < distances.Length - 1 && target >= distances[chosen])

4806 {

4807 target -= distances[chosen++];

4808 }

4809 

4810 centers.Add((double[])matrix[chosen].Clone());

4811 }

4812 

4813 int[] labels = Enumerable.Repeat(-1, matrix.Length).ToArray();

4814 for (int iteration = 0; iteration < 1000; iteration++)

4815 {

4816 bool changed = false;

4817 int[] counts = new int[clusterCount];

4818 double[][] sums = Enumerable.Range(0, clusterCount).Select(_ => new double[matrix[0].Length]).ToArray();

4819 for (int i = 0; i < matrix.Length; i++)

4820 {

4821 int closest = Enumerable.Range(0, clusterCount)

4822 .MinBy(cluster => SquaredDistance(matrix[i], centers[cluster]));

4823 changed |= labels[i] != closest;

4824 labels[i] = closest;

4825 counts[closest]++;

4826 }

4827 

4828 // Move the worst represented member of a nonsingleton cluster to

4829 // each empty cluster. Recompute means from these exact assignments.

4830 for (int empty = 0; empty < clusterCount; empty++)

4831 {

4832 if (counts[empty] != 0)

4833 {

4834 continue;

4835 }

4836 

4837 int moved = Enumerable.Range(0, matrix.Length)

4838 .Where(i => counts[labels[i]] > 1)

4839 .MaxBy(i => SquaredDistance(matrix[i], centers[labels[i]]));

4840 counts[labels[moved]]--;

4841 labels[moved] = empty;

4842 counts[empty]++;

4843 changed = true;

4844 }

4845 

4846 for (int i = 0; i < matrix.Length; i++)

4847 {

4848 for (int d = 0; d < matrix[i].Length; d++)

4849 {

4850 sums[labels[i]][d] += matrix[i][d];

4851 }

4852 }

4853 

4854 for (int cluster = 0; cluster < clusterCount; cluster++)

4855 {

4856 for (int d = 0; d < matrix[0].Length; d++)

4857 {

4858 centers[cluster][d] = sums[cluster][d] / counts[cluster];

4859 }

4860 }

4861 

4862 if (!changed)

4863 {

4864 return (labels, centers.ToArray());

4865 }

4866 }

4867 

4868 throw new InvalidOperationException("K-means did not converge within 1000 iterations.");

4869}

4870 

4871static double SquaredDistance(double[] a, double[] b)

4872{

4873 double distance = 0;

4874 for (int d = 0; d < a.Length; d++)

4875 {

4876 double delta = a[d] - b[d];

4877 distance += delta * delta;

4878 }

4879 

4880 if (!double.IsFinite(distance))

4881 {

4882 throw new InvalidDataException("Embedding distances overflowed; rescale the input.");

4883 }

4884 

4885 return distance;

4886}

4887 

4888// Read the CSV produced by the review-embedding workflow. TextFieldParser

4889// handles quoted JSON vectors, commas, escaped quotes, and multiline reviews.

4890static (double[][] Vectors, int[] Scores) ReadReviews(string path)

4891{

4892 using TextFieldParser csv = new(path);

4893 csv.TextFieldType = FieldType.Delimited;

4894 csv.SetDelimiters(",");

4895 csv.HasFieldsEnclosedInQuotes = true;

4896 string[] header = csv.ReadFields() ?? throw new InvalidDataException("The CSV is empty.");

4897 int embeddingColumn = Array.IndexOf(header, "ada_embedding");

4898 int scoreColumn = Array.IndexOf(header, "Score");

4899 if (embeddingColumn < 0 || scoreColumn < 0)

4900 {

4901 throw new InvalidDataException("Expected ada_embedding and Score columns.");

4902 }

4903 

4904 List<double[]> vectors = [];

4905 List<int> scores = [];

4906 while (!csv.EndOfData)

4907 {

4908 string[] row = csv.ReadFields() ?? throw new InvalidDataException("Missing CSV row.");

4909 if (row.Length != header.Length)

4910 {

4911 throw new InvalidDataException("The CSV row does not match its header.");

4912 }

4913 

4914 double[] vector = JsonSerializer.Deserialize<double[]>(row[embeddingColumn])

4915 ?? throw new InvalidDataException("A review has no embedding.");

4916 if (vector.Length == 0 || vector.Any(value => !double.IsFinite(value)) ||

4917 (vectors.Count > 0 && vector.Length != vectors[0].Length))

4918 {

4919 throw new InvalidDataException("Embeddings must be finite vectors of equal nonzero length.");

4920 }

4921 

4922 int score = int.Parse(row[scoreColumn], CultureInfo.InvariantCulture);

4923 if (score is < 1 or > 5)

4924 {

4925 throw new InvalidDataException("Review scores must be integers from 1 through 5.");

4926 }

4927 

4928 vectors.Add(vector);

4929 scores.Add(score);

4930 }

4931 

4932 if (vectors.Count == 0)

4933 {

4934 throw new InvalidDataException("The CSV has no reviews.");

4935 }

4936 

4937 return (vectors.ToArray(), scores.ToArray());

4938}

4939```

4940 

3728```ruby4941```ruby

3729require "rumale/clustering"4942require "rumale/clustering"

3730 4943 


3817 .getEncoding(com.knuddels.jtokkit.api.EncodingType.CL100K_BASE);5030 .getEncoding(com.knuddels.jtokkit.api.EncodingType.CL100K_BASE);

3818```5031```

3819 5032 

5033```csharp

5034using System;

5035using System.IO;

5036using System.Text.Json;

5037using System.Threading.Tasks;

5038using Microsoft.ML.Tokenizers;

5039 

5040static int NumberOfTokens(string text, string encodingName)

5041{

5042 ArgumentNullException.ThrowIfNull(text);

5043 ArgumentException.ThrowIfNullOrWhiteSpace(encodingName);

5044 TiktokenTokenizer encoding = TiktokenTokenizer.CreateForEncoding(encodingName);

5045 return encoding.CountTokens(text);

5046}

5047 

5048int tokens = NumberOfTokens("tiktoken is great!", "cl100k_base");

5049Console.WriteLine(tokens);

5050```

5051 

3820```ruby5052```ruby

3821require "tiktoken_ruby"5053require "tiktoken_ruby"

3822 5054 

Details

3505ImageIO.write(rgba, "png", new File("mask_alpha.png"));3505ImageIO.write(rgba, "png", new File("mask_alpha.png"));

3506```3506```

3507 3507 

3508```csharp

3509using System.Diagnostics;

3510 

3511namespace OpenAI.Docs.Examples.Images.AddAlphaChannelSample;

3512 

3513internal static class AddAlphaChannel

3514{

3515 private static readonly string[] ProbeArguments =

3516 [

3517 "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=pix_fmt",

3518 "-of", "default=noprint_wrappers=1:nokey=1", "mask.png",

3519 ];

3520 

3521 internal static async Task RunAsync()

3522 {

3523 // Install FFmpeg (including ffprobe) and place the input mask at mask.png.

3524 string pixelFormat = (await RunToolAsync("ffprobe", ProbeArguments)).Trim();

3525 string temporaryPath = $"mask_alpha-{Guid.NewGuid():N}.png";

3526 try

3527 {

3528 _ = await RunToolAsync("ffmpeg", CreateConversionArguments(pixelFormat, temporaryPath));

3529 File.Move(temporaryPath, "mask_alpha.png", overwrite: true);

3530 }

3531 finally

3532 {

3533 // Remove only this invocation's temporary artifact, including on failure.

3534 File.Delete(temporaryPath);

3535 }

3536 }

3537 

3538 internal static string[] CreateConversionArguments(string pixelFormat, string temporaryPath)

3539 {

3540 // Normalize high-bit-depth grayscale before RGB conversion to avoid

3541 // FFmpeg's different gray16-to-RGBA rounding. Ignore the input alpha.

3542 string normalization = pixelFormat switch

3543 {

3544 "gray16be" or "gray16le" => "format=gray,",

3545 "gray" or "ya8" or "pal8" or "monob" or "monow"

3546 or "rgb24" or "bgr24" or "rgba" or "bgra" or "argb" or "abgr"

3547 or "rgb0" or "bgr0" or "0rgb" or "0bgr" or "rgb8" or "bgr8"

3548 or "yuv420p" or "yuv422p" or "yuv444p" or "yuv440p"

3549 or "yuvj420p" or "yuvj422p" or "yuvj444p" or "yuvj440p" => "",

3550 _ => throw new NotSupportedException(

3551 $"Normalize mask pixel format '{pixelFormat}' to 8-bit grayscale first."),

3552 };

3553 const string luminance = "floor((299*r(X,Y)+587*g(X,Y)+114*b(X,Y)+500)/1000)";

3554 string filter = $"{normalization}format=rgba,"

3555 + $"geq=r='{luminance}':g='{luminance}':b='{luminance}':a='{luminance}':interpolation=nearest,"

3556 + "format=rgba";

3557 return

3558 [

3559 "-nostdin", "-hide_banner", "-loglevel", "error", "-y",

3560 "-filter_threads", "1", "-i", "mask.png", "-frames:v", "1",

3561 "-vf", filter, "-pix_fmt", "rgba", "-update", "1", temporaryPath,

3562 ];

3563 }

3564 

3565 private static async Task<string> RunToolAsync(string executable, IEnumerable<string> arguments)

3566 {

3567 ProcessStartInfo start = new(executable)

3568 {

3569 UseShellExecute = false,

3570 RedirectStandardError = true,

3571 RedirectStandardOutput = true,

3572 CreateNoWindow = true,

3573 };

3574 foreach (string argument in arguments)

3575 {

3576 start.ArgumentList.Add(argument);

3577 }

3578 using Process process = Process.Start(start)

3579 ?? throw new InvalidOperationException($"Could not start {executable}.");

3580 Task<string> output = process.StandardOutput.ReadToEndAsync();

3581 Task<string> diagnostics = process.StandardError.ReadToEndAsync();

3582 using CancellationTokenSource timeout = new(TimeSpan.FromSeconds(30));

3583 try

3584 {

3585 await process.WaitForExitAsync(timeout.Token);

3586 }

3587 catch (OperationCanceledException)

3588 {

3589 if (!process.HasExited)

3590 {

3591 process.Kill(entireProcessTree: true);

3592 }

3593 await process.WaitForExitAsync();

3594 await Task.WhenAll(output, diagnostics);

3595 throw new TimeoutException($"{executable} exceeded 30 seconds.");

3596 }

3597 string error = await diagnostics;

3598 string result = await output;

3599 if (process.ExitCode != 0)

3600 {

3601 throw new InvalidOperationException($"{executable} failed: {error}");

3602 }

3603 return result;

3604 }

3605}

3606```

3607 

3508```ruby3608```ruby

3509require "chunky_png"3609require "chunky_png"

3510 3610 

Details

2450}2450}

2451```2451```

2452 2452 

2453```csharp

2454using System.Text;

2455using System.Xml;

2456using System.Xml.Linq;

2457 

2458namespace OpenAI.Docs.Examples.RetrievalExamples.ResultFormatting;

2459 

2460internal static class SampleResultFormattingFunction

2461{

2462 // Application-owned data: formatting does not require a vector-search client.

2463 internal sealed record SearchContent(string Text);

2464 

2465 internal sealed record SearchResult(

2466 string FileId,

2467 string Filename,

2468 IReadOnlyList<SearchContent> Content

2469 );

2470 

2471 internal static string FormatResults(IEnumerable<SearchResult> results)

2472 {

2473 XElement sources = new("sources");

2474 foreach (SearchResult result in results)

2475 {

2476 XElement element = new(

2477 "result",

2478 new XAttribute("file_id", result.FileId),

2479 new XAttribute("file_name", result.Filename)

2480 );

2481 foreach (SearchContent part in result.Content)

2482 {

2483 element.Add(new XElement("content", part.Text));

2484 }

2485 sources.Add(element);

2486 }

2487 StringBuilder output = new();

2488 // Entitize whitespace that XML parsers would otherwise normalize.

2489 using XmlWriter writer = XmlWriter.Create(

2490 output,

2491 new XmlWriterSettings

2492 {

2493 OmitXmlDeclaration = true,

2494 Indent = false,

2495 NewLineHandling = NewLineHandling.Entitize,

2496 CheckCharacters = true,

2497 }

2498 );

2499 writer.WriteStartElement("sources");

2500 foreach (XElement result in sources.Elements())

2501 {

2502 result.WriteTo(writer);

2503 }

2504 writer.WriteFullEndElement();

2505 writer.Flush();

2506 return output.ToString();

2507 }

2508 

2509}

2510```

2511 

2453```ruby2512```ruby

2454def format_results(results)2513def format_results(results)

2455 sources = results.map do |result|2514 sources = results.map do |result|

Details

901}901}

902```902```

903 903 

904```csharp

905using System;

906using System.Diagnostics;

907using System.Globalization;

908using System.IO;

909using System.Text.Json;

910using System.Threading;

911using System.Threading.Tasks;

912 

913namespace OpenAI.Docs.Examples.SpeechToTextLongerInputs;

914 

915internal static class SpeechToTextLongerInputs

916{

917 internal static async Task RunAsync()

918 {

919 // Install FFmpeg and ffprobe on PATH. Supply a PCM WAV at this path.

920 // Retain the first ten minutes (or the entire file when shorter).

921 // Ten minutes does not guarantee a file below the transcription upload limit.

922 const string inputPath = "good_morning.wav";

923 const string outputPath = "good_morning_10.wav";

924 using CancellationTokenSource timeout = new(TimeSpan.FromMinutes(2));

925 AudioInfo input = await ProbeAsync(inputPath, timeout.Token);

926 string temporaryPath = Path.GetFullPath(outputPath) + $".{Guid.NewGuid():N}.tmp.wav";

927 try

928 {

929 // Match the input codec, rate and channels: retain PCM samples without

930 // resampling or reducing their precision, including high-bitrate stereo.

931 // Trimming by sample count gives exactly 600 seconds for longer files.

932 await RunToolAsync("ffmpeg", CreateTrimArguments(input, inputPath, temporaryPath), timeout.Token);

933 AudioInfo output = await ProbeAsync(temporaryPath, timeout.Token);

934 if (Math.Abs(output.DurationMilliseconds - Math.Min(input.DurationMilliseconds, 600_000L)) > 1)

935 throw new InvalidDataException("The trimmed audio duration does not match the requested interval.");

936 File.Move(temporaryPath, outputPath, overwrite: true);

937 string durations = JsonSerializer.Serialize(new

938 {

939 input_ms = input.DurationMilliseconds,

940 output_ms = output.DurationMilliseconds

941 });

942 Console.WriteLine(durations);

943 

944}

945 finally

946 {

947 File.Delete(temporaryPath);

948 }

949 }

950 internal sealed record AudioInfo(string Codec, int SampleRate, long DurationMilliseconds);

951 

952 private static async Task<AudioInfo> ProbeAsync(string path, CancellationToken cancellationToken)

953 {

954 string json = await RunToolAsync("ffprobe",

955 ["-v", "error", "-select_streams", "a:0", "-show_entries",

956 "stream=codec_name,sample_rate:format=duration,format_name", "-of", "json", path],

957 cancellationToken);

958 return ParseAudioInfo(json);

959 }

960 

961 internal static AudioInfo ParseAudioInfo(string json)

962 {

963 using JsonDocument document = JsonDocument.Parse(json);

964 JsonElement format = document.RootElement.GetProperty("format");

965 if (format.GetProperty("format_name").GetString() != "wav")

966 throw new InvalidDataException("Supply a PCM WAV file.");

967 JsonElement streams = document.RootElement.GetProperty("streams");

968 if (streams.GetArrayLength() != 1)

969 throw new InvalidDataException("No audio stream was found.");

970 JsonElement stream = streams[0];

971 string codec = stream.GetProperty("codec_name").GetString()

972 ?? throw new InvalidDataException("Missing WAV codec.");

973 if (codec is not ("pcm_u8" or "pcm_s16le" or "pcm_s24le" or "pcm_s32le" or

974 "pcm_f32le" or "pcm_f64le"))

975 throw new InvalidDataException($"This sample requires uncompressed little-endian PCM WAV; received {codec}.");

976 int sampleRate = int.Parse(stream.GetProperty("sample_rate").GetString()!, CultureInfo.InvariantCulture);

977 double seconds = double.Parse(format.GetProperty("duration").GetString()!, CultureInfo.InvariantCulture);

978 if (sampleRate <= 0 || !double.IsFinite(seconds) || seconds < 0)

979 throw new InvalidDataException("Invalid audio sample rate or duration.");

980 return new AudioInfo(codec, sampleRate,

981 checked((long)Math.Round(seconds * 1000, MidpointRounding.AwayFromZero)));

982 }

983 

984 internal static string[] CreateTrimArguments(AudioInfo input, string inputPath, string temporaryPath)

985 {

986 long retainedFrames = checked(600L * input.SampleRate);

987 return

988 [

989 "-v", "error", "-nostdin", "-n", "-i", inputPath, "-map", "0:a:0",

990 "-af", $"atrim=end_sample={retainedFrames.ToString(CultureInfo.InvariantCulture)}",

991 "-c:a", input.Codec, "-flags:a", "+bitexact", "-fflags", "+bitexact",

992 "-map_metadata", "-1", temporaryPath,

993 ];

994 }

995 

996 private static async Task<string> RunToolAsync(

997 string executable, string[] arguments, CancellationToken cancellationToken)

998 {

999 ProcessStartInfo startInfo = new(executable)

1000 {

1001 RedirectStandardOutput = true,

1002 RedirectStandardError = true,

1003 UseShellExecute = false,

1004 CreateNoWindow = true

1005 };

1006 foreach (string argument in arguments)

1007 startInfo.ArgumentList.Add(argument);

1008 using Process process = Process.Start(startInfo)

1009 ?? throw new InvalidOperationException($"Could not start {executable}.");

1010 Task<string> stdout = process.StandardOutput.ReadToEndAsync(CancellationToken.None);

1011 Task<string> stderr = process.StandardError.ReadToEndAsync(CancellationToken.None);

1012 try

1013 {

1014 await process.WaitForExitAsync(cancellationToken);

1015 }

1016 catch (OperationCanceledException)

1017 {

1018 if (!process.HasExited)

1019 process.Kill(entireProcessTree: true);

1020 await process.WaitForExitAsync(CancellationToken.None);

1021 await Task.WhenAll(stdout, stderr);

1022 throw;

1023 }

1024 string output = await stdout;

1025 string diagnostic = await stderr;

1026 if (process.ExitCode != 0)

1027 throw new InvalidOperationException($"{executable} exited with {process.ExitCode}: {diagnostic}");

1028 return output;

1029 }

1030}

1031```

1032 

904```ruby1033```ruby

905# standard:disable Lint/UselessAssignment -- Preserve named results for the next workflow step.1034# standard:disable Lint/UselessAssignment -- Preserve named results for the next workflow step.

906require "open3"1035require "open3"

Details

455 455 

456 456 

457 457 

458 

459 

460 

461Use Go 1.26 or later and `playwright-go` v0.5200.1 from the [Go sample module](https://github.com/openai/developers-website/tree/main/src/content/platform/go-examples). Start at the repository root to install the driver and Chromium.

462 

463```bash

464cd src/content/platform/go-examples

465go run github.com/playwright-community/playwright-go/cmd/playwright@v0.5200.1 install chromium

466```

467 

468If Linux system libraries are missing, run the same versioned command with `install --with-deps chromium`. You need permission to install operating-system packages.

469 

470Browser actions and screenshots belong inside the callback passed to `withBrowserPage`, before its cleanup.

471 

472**Runtime helper requirement**

473 

474The runtime helper requires a preinstalled matching driver and browser. It does not download them.

475 

476 

477 

478 

458Then launch a browser instance. Keep the browser and page alive while you run the remaining steps.479Then launch a browser instance. Keep the browser and page alive while you run the remaining steps.

459 480 

460 481 


510 page = browser.new_page(viewport={"width": 1280, "height": 720})531 page = browser.new_page(viewport={"width": 1280, "height": 720})

511```532```

512 533 

534```go

535import (

536 "errors"

537 "fmt"

538 "time"

539 

540 "github.com/playwright-community/playwright-go"

541)

542 

543// withBrowserPage owns the browser lifecycle around your application's page operations.

544// For example, the callback can call page.SetContent with application-owned HTML.

545func withBrowserPage(visit func(playwright.Page) error) (err error) {

546 // Runtime prerequisites must be installed separately; this sample never downloads browsers.

547 pw, err := playwright.Run()

548 if err != nil {

549 return err

550 }

551 defer func() { err = errors.Join(err, pw.Stop()) }()

552 browser, err := pw.Chromium.Launch(playwright.BrowserTypeLaunchOptions{

553 Headless: playwright.Bool(true), ChromiumSandbox: playwright.Bool(true),

554 Env: map[string]string{}, Timeout: playwright.Float(30000),

555 Args: []string{"--disable-extensions", "--disable-file-system"},

556 })

557 if err != nil {

558 return err

559 }

560 defer func() { err = errors.Join(err, browser.Close()) }()

561 deadlineResult := make(chan error, 1)

562 deadline := time.AfterFunc(5*time.Minute, func() {

563 deadlineResult <- errors.Join(fmt.Errorf("browser page lifetime exceeded five minutes"), browser.Close())

564 })

565 defer func() {

566 if !deadline.Stop() {

567 err = errors.Join(err, <-deadlineResult)

568 }

569 }()

570 

571 context, err := browser.NewContext(playwright.BrowserNewContextOptions{

572 Viewport: &playwright.Size{

573 Width: 1280,

574 Height: 720,

575 },

576 })

577 if err != nil {

578 return err

579 }

580 defer func() { err = errors.Join(err, context.Close()) }()

581 page, err := context.NewPage()

582 if err != nil {

583 return err

584 }

585 page.SetDefaultTimeout(10000)

586 return visit(page)

587}

588```

589 

513```java590```java

514import com.microsoft.playwright.*;591import com.microsoft.playwright.*;

515import com.microsoft.playwright.options.*;592import com.microsoft.playwright.options.*;


534 611 

535```612```

536 613 

614```csharp

615using System;

616using System.Collections.Generic;

617using System.IO;

618using System.Text.Json;

619using System.Threading;

620using System.Threading.Tasks;

621using Microsoft.Playwright;

622// Microsoft.Playwright 1.52.0 and its matching Chromium installation.

623 

624static async Task CloseAtDeadlineAsync(IBrowser browser, CancellationToken cancellationToken)

625{

626 try { await Task.Delay(TimeSpan.FromMinutes(5), cancellationToken); }

627 catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { return; }

628 await browser.CloseAsync();

629 throw new TimeoutException("Browser page lifetime exceeded five minutes.");

630}

631 

632static BrowserTypeLaunchOptions CreateLaunchOptions() => new()

633{

634 Headless = true,

635 ChromiumSandbox = true,

636 Env = new Dictionary<string, string>(),

637 Timeout = 30_000,

638 Args = ["--disable-extensions", "--disable-file-system"],

639};

640 

641static BrowserNewContextOptions CreateContextOptions() => new()

642{

643 ViewportSize = new() { Width = 1280, Height = 720 },

644};

645 

646using IPlaywright playwright = await Playwright.CreateAsync();

647await using IBrowser browser = await playwright.Chromium.LaunchAsync(CreateLaunchOptions());

648await using IBrowserContext context = await browser.NewContextAsync(CreateContextOptions());

649using CancellationTokenSource lifetime = new();

650Task deadline = CloseAtDeadlineAsync(browser, lifetime.Token);

651try

652{

653 IPage page = await context.NewPageAsync();

654 page.SetDefaultTimeout(10_000);

655 // Subsequent browser actions and screenshots before cleanup.

656 

657}

658finally

659{

660 await lifetime.CancelAsync();

661 await deadline;

662}

663```

664 

537```ruby665```ruby

538require "playwright"666require "playwright"

539 667 


706vm = VM(display=":99", container_name="cua-image")834vm = VM(display=":99", container_name="cua-image")

707```835```

708 836 

837```go

838import (

839 "bytes"

840 "context"

841 "fmt"

842 "os/exec"

843 "sort"

844 "time"

845)

846 

847type VM struct {

848 Display string

849 ContainerName string

850 Executions int

851}

852 

853// dockerExec preserves argument boundaries and returns stdout as bytes, including PNGs.

854func (vm *VM) dockerExec(executable string, arguments []string, environment map[string]string) ([]byte, error) {

855 args := []string{"exec"}

856 names := make([]string, 0, len(environment))

857 for name := range environment {

858 names = append(names, name)

859 }

860 sort.Strings(names)

861 for _, name := range names {

862 args = append(args, "--env", name+"="+environment[name])

863 }

864 args = append(args, vm.ContainerName, executable)

865 args = append(args, arguments...)

866 ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)

867 defer cancel()

868 command := exec.CommandContext(ctx, "docker", args...)

869 var stderr bytes.Buffer

870 command.Stderr = &stderr

871 vm.Executions++

872 output, err := command.Output()

873 if err != nil {

874 return nil, fmt.Errorf("docker exec %s: %w: %s", executable, err, stderr.String())

875 }

876 return output, nil

877}

878 

879func (vm *VM) xdotool(arguments ...string) error {

880 _, err := vm.dockerExec("xdotool", arguments, map[string]string{"DISPLAY": vm.Display})

881 return err

882}

883```

884 

709```java885```java

710import com.openai.core.ObjectMappers;886import com.openai.core.ObjectMappers;

711import java.nio.charset.StandardCharsets;887import java.nio.charset.StandardCharsets;


749}925}

750```926```

751 927 

928```csharp

929using System;

930using System.Collections.Generic;

931using System.Diagnostics;

932using System.IO;

933using System.Linq;

934using System.Text;

935using System.Text.Json;

936using System.Threading;

937using System.Threading.Tasks;

938 

939internal sealed record VM(string Display, string ContainerName)

940{

941 internal int Executions { get; set; }

942}

943 

944internal static ProcessStartInfo CreateDockerStartInfo(

945 VM vm, string executable, IReadOnlyList<string> arguments,

946 IReadOnlyDictionary<string, string>? environment = null)

947{

948 ProcessStartInfo start = new("docker")

949 {

950 UseShellExecute = false,

951 RedirectStandardInput = true,

952 RedirectStandardOutput = true,

953 RedirectStandardError = true,

954 StandardErrorEncoding = Encoding.UTF8,

955 };

956 start.ArgumentList.Add("exec");

957 if (environment is not null)

958 {

959 foreach ((string name, string value) in environment)

960 {

961 start.ArgumentList.Add("--env");

962 start.ArgumentList.Add($"{name}={value}");

963 }

964 }

965 start.ArgumentList.Add(vm.ContainerName);

966 start.ArgumentList.Add(executable);

967 foreach (string argument in arguments)

968 {

969 start.ArgumentList.Add(argument);

970 }

971 return start;

972}

973 

974// ArgumentList avoids shell expansion; stdout remains binary throughout.

975internal static async Task<byte[]> DockerExecAsync(

976 VM vm, string executable, IReadOnlyList<string> arguments,

977 IReadOnlyDictionary<string, string>? environment = null)

978{

979 ProcessStartInfo start = CreateDockerStartInfo(vm, executable, arguments, environment);

980 using Process process = new() { StartInfo = start };

981 vm.Executions++;

982 if (!process.Start())

983 {

984 throw new InvalidOperationException("Could not start Docker.");

985 }

986 process.StandardInput.Close();

987 using CancellationTokenSource timeout = new(TimeSpan.FromSeconds(30));

988 using MemoryStream stdout = new();

989 try

990 {

991 Task copy = process.StandardOutput.BaseStream.CopyToAsync(stdout, timeout.Token);

992 Task<string> stderr = process.StandardError.ReadToEndAsync(timeout.Token);

993 await Task.WhenAll(copy, stderr, process.WaitForExitAsync(timeout.Token));

994 if (process.ExitCode != 0)

995 {

996 throw new InvalidOperationException($"docker exec {executable} failed ({process.ExitCode}): {await stderr}");

997 }

998 return stdout.ToArray();

999 }

1000 finally

1001 {

1002 if (!process.HasExited)

1003 {

1004 process.Kill(entireProcessTree: true);

1005 }

1006 await process.WaitForExitAsync();

1007 }

1008}

1009 

1010internal static async Task XdotoolAsync(VM vm, params string[] arguments)

1011{

1012 await DockerExecAsync(vm, "xdotool", arguments, new Dictionary<string, string> { ["DISPLAY"] = vm.Display });

1013}

1014```

1015 

752```ruby1016```ruby

753def docker_exec(container_name, executable, args, decode: true, env: {})1017def docker_exec(container_name, executable, args, decode: true, env: {})

754 environment = env.flat_map { |name, value| ["--env", "#{name}=#{value}"] }1018 environment = env.flat_map { |name, value| ["--env", "#{name}=#{value}"] }


966 return [(point.x, point.y) for point in path]1230 return [(point.x, point.y) for point in path]

967```1231```

968 1232 

1233```go

1234import (

1235 "fmt"

1236 

1237 "github.com/openai/openai-go/v3/responses"

1238 "github.com/playwright-community/playwright-go"

1239)

1240 

1241func normalizeKey(key string) string {

1242 switch key {

1243 case "ENTER", "RETURN":

1244 return "Enter"

1245 case "ESC", "ESCAPE":

1246 return "Escape"

1247 case "TAB":

1248 return "Tab"

1249 case "SPACE":

1250 return "Space"

1251 case "BACKSPACE":

1252 return "Backspace"

1253 case "DELETE", "DEL":

1254 return "Delete"

1255 case "HOME":

1256 return "Home"

1257 case "END":

1258 return "End"

1259 case "PAGEUP":

1260 return "PageUp"

1261 case "PAGEDOWN":

1262 return "PageDown"

1263 case "UP", "ARROWUP":

1264 return "ArrowUp"

1265 case "DOWN", "ARROWDOWN":

1266 return "ArrowDown"

1267 case "LEFT", "ARROWLEFT":

1268 return "ArrowLeft"

1269 case "RIGHT", "ARROWRIGHT":

1270 return "ArrowRight"

1271 case "CTRL", "CONTROL":

1272 return "Control"

1273 case "SHIFT":

1274 return "Shift"

1275 case "ALT", "OPTION":

1276 return "Alt"

1277 case "META", "CMD", "COMMAND":

1278 return "Meta"

1279 default:

1280 return key

1281 }

1282}

1283 

1284func normalizeButton(button string) (playwright.MouseButton, error) {

1285 switch button {

1286 case "left":

1287 return playwright.MouseButton("left"), nil

1288 case "wheel":

1289 return playwright.MouseButton("middle"), nil

1290 case "right":

1291 return playwright.MouseButton("right"), nil

1292 default:

1293 return "", fmt.Errorf("unsupported mouse button: %s", button)

1294 }

1295}

1296 

1297func normalizeDragPath(path []responses.ComputerActionDragPath) [][2]int64 {

1298 result := make([][2]int64, len(path))

1299 for i, point := range path {

1300 result[i] = [2]int64{point.X, point.Y}

1301 }

1302 return result

1303}

1304```

1305 

969```java1306```java

970import com.microsoft.playwright.*;1307import com.microsoft.playwright.*;

971import com.microsoft.playwright.options.*;1308import com.microsoft.playwright.options.*;


1014}1351}

1015```1352```

1016 1353 

1354```csharp

1355using System;

1356using System.Collections.Generic;

1357using System.IO;

1358using System.Linq;

1359using System.Text.Json;

1360using System.Threading;

1361using System.Threading.Tasks;

1362using Microsoft.Playwright;

1363 

1364internal static string NormalizeKey(string key) => key switch

1365{

1366 "ENTER" or "RETURN" => "Enter",

1367 "ESC" or "ESCAPE" => "Escape",

1368 "TAB" => "Tab",

1369 "SPACE" => "Space",

1370 "BACKSPACE" => "Backspace",

1371 "DELETE" or "DEL" => "Delete",

1372 "HOME" => "Home",

1373 "END" => "End",

1374 "PAGEUP" => "PageUp",

1375 "PAGEDOWN" => "PageDown",

1376 "UP" or "ARROWUP" => "ArrowUp",

1377 "DOWN" or "ARROWDOWN" => "ArrowDown",

1378 "LEFT" or "ARROWLEFT" => "ArrowLeft",

1379 "RIGHT" or "ARROWRIGHT" => "ArrowRight",

1380 "CTRL" or "CONTROL" => "Control",

1381 "SHIFT" => "Shift",

1382 "ALT" or "OPTION" => "Alt",

1383 "META" or "CMD" or "COMMAND" => "Meta",

1384 _ => key,

1385};

1386 

1387internal static MouseButton NormalizeButton(string button) => button switch

1388{

1389 "left" => MouseButton.Left,

1390 "wheel" => MouseButton.Middle,

1391 "right" => MouseButton.Right,

1392 _ => throw new ArgumentException($"Unsupported mouse button: {button}", nameof(button)),

1393};

1394 

1395internal static double[][] NormalizeDragPath(JsonElement path)

1396{

1397 if (path.ValueKind != JsonValueKind.Array)

1398 {

1399 throw new ArgumentException("A drag path must be an array.", nameof(path));

1400 }

1401 return path.EnumerateArray().Select(point =>

1402 {

1403 double[] coordinates = point.ValueKind switch

1404 {

1405 JsonValueKind.Array when point.GetArrayLength() >= 2 =>

1406 [point[0].GetDouble(), point[1].GetDouble()],

1407 JsonValueKind.Object =>

1408 [point.GetProperty("x").GetDouble(), point.GetProperty("y").GetDouble()],

1409 _ => throw new ArgumentException("Expected coordinate pairs or objects.", nameof(path)),

1410 };

1411 if (!coordinates.All(double.IsFinite))

1412 {

1413 throw new ArgumentException("Coordinates must be finite.", nameof(path));

1414 }

1415 return coordinates;

1416 }).ToArray();

1417}

1418```

1419 

1017```ruby1420```ruby

1018def normalize_key(key)1421def normalize_key(key)

1019 names = {1422 names = {


1282 return [(point.x, point.y) for point in path]1685 return [(point.x, point.y) for point in path]

1283```1686```

1284 1687 

1688```go

1689import (

1690 "github.com/openai/openai-go/v3/responses"

1691 "math"

1692)

1693 

1694type InvalidInputError struct{ Message string }

1695 

1696func (e *InvalidInputError) Error() string { return e.Message }

1697 

1698func normalizeKey(key string) string {

1699 switch key {

1700 case "ENTER", "RETURN":

1701 return "Return"

1702 case "ESC", "ESCAPE":

1703 return "Escape"

1704 case "TAB":

1705 return "Tab"

1706 case "SPACE":

1707 return "space"

1708 case "BACKSPACE":

1709 return "BackSpace"

1710 case "DELETE", "DEL":

1711 return "Delete"

1712 case "HOME":

1713 return "Home"

1714 case "END":

1715 return "End"

1716 case "PAGEUP":

1717 return "Page_Up"

1718 case "PAGEDOWN":

1719 return "Page_Down"

1720 case "UP", "ARROWUP":

1721 return "Up"

1722 case "DOWN", "ARROWDOWN":

1723 return "Down"

1724 case "LEFT", "ARROWLEFT":

1725 return "Left"

1726 case "RIGHT", "ARROWRIGHT":

1727 return "Right"

1728 case "CTRL", "CONTROL":

1729 return "ctrl"

1730 case "SHIFT":

1731 return "shift"

1732 case "ALT", "OPTION":

1733 return "alt"

1734 case "META", "CMD", "COMMAND":

1735 return "super"

1736 default:

1737 return key

1738 }

1739}

1740 

1741func normalizeButton(button string) (int, error) {

1742 switch button {

1743 case "left":

1744 return 1, nil

1745 case "wheel":

1746 return 2, nil

1747 case "right":

1748 return 3, nil

1749 case "back":

1750 return 8, nil

1751 case "forward":

1752 return 9, nil

1753 default:

1754 return 0, &InvalidInputError{"Unsupported mouse button: " + button}

1755 }

1756}

1757 

1758func normalizeDragPath(path []responses.ComputerActionDragPath) [][2]int64 {

1759 result := make([][2]int64, 0, len(path))

1760 for _, point := range path {

1761 result = append(result, [2]int64{point.X, point.Y})

1762 }

1763 return result

1764}

1765 

1766func scrollButtons(x, y int64) []int {

1767 buttons := []int{}

1768 for _, direction := range [][3]int64{{y, 4, 5}, {x, 6, 7}} {

1769 delta := direction[0]

1770 if delta == 0 {

1771 continue

1772 }

1773 button := direction[2]

1774 if delta < 0 {

1775 button = direction[1]

1776 }

1777 // Python round and Java rint use ties-to-even (Go math.Round does not).

1778 clicks := max(1, int(math.Abs(math.RoundToEven(float64(delta)/100))))

1779 for i := 0; i < clicks; i++ {

1780 buttons = append(buttons, int(button))

1781 }

1782 }

1783 return buttons

1784}

1785```

1786 

1285```java1787```java

1286import com.openai.core.ObjectMappers;1788import com.openai.core.ObjectMappers;

1287import com.openai.models.responses.ComputerAction;1789import com.openai.models.responses.ComputerAction;


1341}1843}

1342```1844```

1343 1845 

1846```csharp

1847using System;

1848using System.Collections.Generic;

1849using System.Diagnostics;

1850using System.IO;

1851using System.Linq;

1852using System.Text;

1853using System.Text.Json;

1854using System.Text.Json.Serialization;

1855using System.Threading;

1856using System.Threading.Tasks;

1857 

1858internal sealed record Point(

1859 [property: JsonPropertyName("x")] long X,

1860 [property: JsonPropertyName("y")] long Y);

1861 

1862internal static string NormalizeKey(string key) => key switch

1863{

1864 "ENTER" or "RETURN" => "Return",

1865 "ESC" or "ESCAPE" => "Escape",

1866 "TAB" => "Tab",

1867 "SPACE" => "space",

1868 "BACKSPACE" => "BackSpace",

1869 "DELETE" or "DEL" => "Delete",

1870 "HOME" => "Home",

1871 "END" => "End",

1872 "PAGEUP" => "Page_Up",

1873 "PAGEDOWN" => "Page_Down",

1874 "UP" or "ARROWUP" => "Up",

1875 "DOWN" or "ARROWDOWN" => "Down",

1876 "LEFT" or "ARROWLEFT" => "Left",

1877 "RIGHT" or "ARROWRIGHT" => "Right",

1878 "CTRL" or "CONTROL" => "ctrl",

1879 "SHIFT" => "shift",

1880 "ALT" or "OPTION" => "alt",

1881 "META" or "CMD" or "COMMAND" => "super",

1882 _ => key,

1883};

1884 

1885internal static int NormalizeButton(string button) => button switch

1886{

1887 "left" => 1,

1888 "wheel" => 2,

1889 "right" => 3,

1890 "back" => 8,

1891 "forward" => 9,

1892 _ => throw new ArgumentException($"Unsupported mouse button: {button}", nameof(button)),

1893};

1894 

1895internal static long[][] NormalizeDragPath(IReadOnlyList<Point> path) =>

1896 path.Select(point => new[] { point.X, point.Y }).ToArray();

1897 

1898internal static List<int> ScrollButtons(long x, long y)

1899{

1900 List<int> buttons = [];

1901 foreach ((long delta, int negative, int positive) in new[] { (y, 4, 5), (x, 6, 7) })

1902 {

1903 if (delta == 0)

1904 {

1905 continue;

1906 }

1907 int button = delta < 0 ? negative : positive;

1908 // Match the Python reference's round-to-even behavior, including half steps.

1909 int clicks = Math.Max(1, checked((int)Math.Abs(Math.Round(delta / 100.0, MidpointRounding.ToEven))));

1910 for (int index = 0; index < clicks; index++)

1911 {

1912 buttons.Add(button);

1913 }

1914 }

1915 return buttons;

1916}

1917```

1918 

1344```ruby1919```ruby

1345def normalize_xdotool_key(key)1920def normalize_xdotool_key(key)

1346 names = {1921 names = {


1575 raise ValueError(f"Unsupported action: {action.type}")2150 raise ValueError(f"Unsupported action: {action.type}")

1576```2151```

1577 2152 

1578```java2153```go

1579import com.microsoft.playwright.*;2154import (

1580import com.microsoft.playwright.options.*;2155 "errors"

1581import com.openai.core.ObjectMappers;2156 "fmt"

1582import com.openai.models.responses.ComputerAction;2157 "strings"

1583import java.nio.file.*;2158 "time"

1584import java.util.*;

1585 2159 

2160 "github.com/openai/openai-go/v3/responses"

2161 "github.com/playwright-community/playwright-go"

2162)

1586 2163 

2164func normalizeKey(key string) string {

2165 switch key {

2166 case "ENTER", "RETURN":

2167 return "Enter"

2168 case "ESC", "ESCAPE":

2169 return "Escape"

2170 case "TAB":

2171 return "Tab"

2172 case "SPACE":

2173 return "Space"

2174 case "BACKSPACE":

2175 return "Backspace"

2176 case "DELETE", "DEL":

2177 return "Delete"

2178 case "HOME":

2179 return "Home"

2180 case "END":

2181 return "End"

2182 case "PAGEUP":

2183 return "PageUp"

2184 case "PAGEDOWN":

2185 return "PageDown"

2186 case "UP", "ARROWUP":

2187 return "ArrowUp"

2188 case "DOWN", "ARROWDOWN":

2189 return "ArrowDown"

2190 case "LEFT", "ARROWLEFT":

2191 return "ArrowLeft"

2192 case "RIGHT", "ARROWRIGHT":

2193 return "ArrowRight"

2194 case "CTRL", "CONTROL":

2195 return "Control"

2196 case "SHIFT":

2197 return "Shift"

2198 case "ALT", "OPTION":

2199 return "Alt"

2200 case "META", "CMD", "COMMAND":

2201 return "Meta"

2202 default:

2203 return key

2204 }

2205}

1587 2206 

1588static void handleComputerActions(Page page, List<ComputerAction> actions) {2207func normalizeButton(button string) (playwright.MouseButton, error) {

1589 for (var action : actions) {2208 switch button {

1590 List<String> keys = List.of();2209 case "left":

1591 Runnable operation;2210 return playwright.MouseButton("left"), nil

1592 if (action.isClick()) {2211 case "wheel":

1593 var click = action.asClick();2212 return playwright.MouseButton("middle"), nil

1594 keys = click.keys().orElse(List.of());2213 case "right":

1595 operation =2214 return playwright.MouseButton("right"), nil

1596 () ->2215 default:

1597 page.mouse()2216 return "", fmt.Errorf("unsupported mouse button: %s", button)

1598 .click(2217 }

1599 click.x(),2218}

2219 

2220func normalizeDragPath(path []responses.ComputerActionDragPath) [][2]int64 {

2221 result := make([][2]int64, len(path))

2222 for i, point := range path {

2223 result[i] = [2]int64{point.X, point.Y}

2224 }

2225 return result

2226}

2227 

2228func handleComputerActions(page playwright.Page, actions []responses.ComputerActionUnion) error {

2229 for _, action := range actions {

2230 var operation func() error

2231 switch action.Type {

2232 case "click":

2233 button, err := normalizeButton(action.Button)

2234 if err != nil {

2235 return err

2236 }

2237 operation = func() error {

2238 return page.Mouse().Click(float64(action.X), float64(action.Y), playwright.MouseClickOptions{Button: &button})

2239 }

2240 case "double_click":

2241 operation = func() error { return page.Mouse().Dblclick(float64(action.X), float64(action.Y)) }

2242 case "move":

2243 operation = func() error { return page.Mouse().Move(float64(action.X), float64(action.Y)) }

2244 case "drag":

2245 path := normalizeDragPath(action.Path)

2246 if len(path) < 2 {

2247 return fmt.Errorf("drag requires at least two points")

2248 }

2249 operation = func() (err error) {

2250 if err = page.Mouse().Move(float64(path[0][0]), float64(path[0][1])); err != nil {

2251 return err

2252 }

2253 if err = page.Mouse().Down(); err != nil {

2254 return err

2255 }

2256 defer func() { err = errors.Join(err, page.Mouse().Up()) }()

2257 for _, point := range path[1:] {

2258 if err = page.Mouse().Move(float64(point[0]), float64(point[1])); err != nil {

2259 return err

2260 }

2261 }

2262 return nil

2263 }

2264 case "scroll":

2265 operation = func() error {

2266 if err := page.Mouse().Move(float64(action.X), float64(action.Y)); err != nil {

2267 return err

2268 }

2269 return page.Mouse().Wheel(float64(action.ScrollX), float64(action.ScrollY))

2270 }

2271 case "keypress":

2272 keys := make([]string, len(action.Keys))

2273 for i, key := range action.Keys {

2274 keys[i] = normalizeKey(key)

2275 }

2276 if len(keys) == 0 {

2277 return fmt.Errorf("keypress requires at least one key")

2278 }

2279 if err := page.Keyboard().Press(strings.Join(keys, "+")); err != nil {

2280 return err

2281 }

2282 continue

2283 case "type":

2284 if err := page.Keyboard().InsertText(action.Text); err != nil {

2285 return err

2286 }

2287 continue

2288 case "wait":

2289 time.Sleep(2 * time.Second)

2290 continue

2291 case "screenshot":

2292 continue // The caller captures the page after the batch.

2293 default:

2294 return fmt.Errorf("unsupported computer action: %s", action.Type)

2295 }

2296 if len(action.Keys) != 0 {

2297 return fmt.Errorf("use the modifier-aware handler")

2298 }

2299 if err := operation(); err != nil {

2300 return err

2301 }

2302 }

2303 return nil

2304}

2305```

2306 

2307```java

2308import com.microsoft.playwright.*;

2309import com.microsoft.playwright.options.*;

2310import com.openai.core.ObjectMappers;

2311import com.openai.models.responses.ComputerAction;

2312import java.nio.file.*;

2313import java.util.*;

2314 

2315 

2316 

2317static void handleComputerActions(Page page, List<ComputerAction> actions) {

2318 for (var action : actions) {

2319 List<String> keys = List.of();

2320 Runnable operation;

2321 if (action.isClick()) {

2322 var click = action.asClick();

2323 keys = click.keys().orElse(List.of());

2324 operation =

2325 () ->

2326 page.mouse()

2327 .click(

2328 click.x(),

1600 click.y(),2329 click.y(),

1601 new Mouse.ClickOptions()2330 new Mouse.ClickOptions()

1602 .setButton(normalizeButton(click.button().toString())));2331 .setButton(normalizeButton(click.button().toString())));


1655}2384}

1656```2385```

1657 2386 

2387```csharp

2388using System;

2389using System.Collections.Generic;

2390using System.Diagnostics;

2391using System.IO;

2392using System.Linq;

2393using System.Runtime.ExceptionServices;

2394using System.Text.Json;

2395using System.Threading;

2396using System.Threading.Tasks;

2397using Microsoft.Playwright;

2398 

2399internal static string NormalizeKey(string key) => key switch

2400{

2401 "ENTER" or "RETURN" => "Enter",

2402 "ESC" or "ESCAPE" => "Escape",

2403 "TAB" => "Tab",

2404 "SPACE" => "Space",

2405 "BACKSPACE" => "Backspace",

2406 "DELETE" or "DEL" => "Delete",

2407 "HOME" => "Home",

2408 "END" => "End",

2409 "PAGEUP" => "PageUp",

2410 "PAGEDOWN" => "PageDown",

2411 "UP" or "ARROWUP" => "ArrowUp",

2412 "DOWN" or "ARROWDOWN" => "ArrowDown",

2413 "LEFT" or "ARROWLEFT" => "ArrowLeft",

2414 "RIGHT" or "ARROWRIGHT" => "ArrowRight",

2415 "CTRL" or "CONTROL" => "Control",

2416 "SHIFT" => "Shift",

2417 "ALT" or "OPTION" => "Alt",

2418 "META" or "CMD" or "COMMAND" => "Meta",

2419 _ => key,

2420};

2421 

2422internal static MouseButton NormalizeButton(string button) => button switch

2423{

2424 "left" => MouseButton.Left,

2425 "wheel" => MouseButton.Middle,

2426 "right" => MouseButton.Right,

2427 _ => throw new ArgumentException($"Unsupported mouse button: {button}", nameof(button)),

2428};

2429 

2430internal static long[][] NormalizeDragPath(JsonElement path) => path.EnumerateArray()

2431 .Select(point => new[] { point.GetProperty("x").GetInt64(), point.GetProperty("y").GetInt64() })

2432 .ToArray();

2433 

2434// These JSON actions are application inputs, not missing OpenAI SDK types.

2435internal static async Task HandleComputerActionsAsync(IPage page, IEnumerable<JsonElement> actions)

2436{

2437 foreach (JsonElement action in actions)

2438 {

2439 string type = action.GetProperty("type").GetString()

2440 ?? throw new ArgumentException("Action type is required.");

2441 string[] keys = action.TryGetProperty("keys", out JsonElement keyValues)

2442 ? keyValues.EnumerateArray().Select(key => key.GetString()

2443 ?? throw new ArgumentException("Keys must be strings.")).ToArray() : [];

2444 Func<Task> operation;

2445 switch (type)

2446 {

2447 case "click":

2448 MouseButton button = NormalizeButton(action.GetProperty("button").GetString()

2449 ?? throw new ArgumentException("Button is required."));

2450 operation = () => page.Mouse.ClickAsync(action.GetProperty("x").GetInt64(),

2451 action.GetProperty("y").GetInt64(), new() { Button = button });

2452 break;

2453 case "double_click":

2454 operation = () => page.Mouse.DblClickAsync(

2455 action.GetProperty("x").GetInt64(),

2456 action.GetProperty("y").GetInt64());

2457 break;

2458 case "move":

2459 operation = () => page.Mouse.MoveAsync(

2460 action.GetProperty("x").GetInt64(),

2461 action.GetProperty("y").GetInt64());

2462 break;

2463 case "drag":

2464 long[][] path = NormalizeDragPath(action.GetProperty("path"));

2465 if (path.Length < 2) throw new ArgumentException("Drag requires at least two points.");

2466 operation = async () =>

2467 {

2468 await page.Mouse.MoveAsync(path[0][0], path[0][1]);

2469 await page.Mouse.DownAsync();

2470 Exception? operationError = null;

2471 try

2472 {

2473 foreach (long[] point in path.Skip(1)) await page.Mouse.MoveAsync(point[0], point[1]);

2474 }

2475 catch (Exception error)

2476 {

2477 operationError = error;

2478 }

2479 finally

2480 {

2481 try { await page.Mouse.UpAsync(); }

2482 catch (Exception releaseError)

2483 {

2484 operationError = operationError is null

2485 ? releaseError : new AggregateException(operationError, releaseError);

2486 }

2487 }

2488 if (operationError is not null) ExceptionDispatchInfo.Capture(operationError).Throw();

2489 };

2490 break;

2491 case "scroll":

2492 operation = async () =>

2493 {

2494 await page.Mouse.MoveAsync(

2495 action.GetProperty("x").GetInt64(),

2496 action.GetProperty("y").GetInt64());

2497 await page.Mouse.WheelAsync(

2498 action.GetProperty("scroll_x").GetInt64(),

2499 action.GetProperty("scroll_y").GetInt64());

2500 };

2501 break;

2502 case "keypress":

2503 if (keys.Length == 0) throw new ArgumentException("Keypress requires at least one key.");

2504 await page.Keyboard.PressAsync(string.Join("+", keys.Select(NormalizeKey)));

2505 continue;

2506 case "type":

2507 await page.Keyboard.InsertTextAsync(action.GetProperty("text").GetString()

2508 ?? throw new ArgumentException("Text is required."));

2509 continue;

2510 case "wait":

2511 await Task.Delay(TimeSpan.FromSeconds(2));

2512 continue;

2513 case "screenshot":

2514 continue; // The caller captures the page after the batch.

2515 default:

2516 throw new ArgumentException($"Unsupported computer action: {type}");

2517 }

2518 if (keys.Length != 0) throw new ArgumentException("Use the modifier-aware handler.");

2519 await operation();

2520 }

2521}

2522```

2523 

1658```ruby2524```ruby

1659def perform_browser_action(page, action)2525def perform_browser_action(page, action)

1660 case action.type2526 case action.type


1945 raise ValueError(f"Unsupported action: {action.type}")2811 raise ValueError(f"Unsupported action: {action.type}")

1946```2812```

1947 2813 

2814```go

2815import (

2816 "errors"

2817 "fmt"

2818 "github.com/openai/openai-go/v3/responses"

2819 "time"

2820)

2821 

2822func withModifiers(vm *VM, keys []string, operation func() error) (err error) {

2823 pressed := []string{}

2824 defer func() {

2825 // Attempt every release even if one release fails, retaining the original failure.

2826 for i := len(pressed) - 1; i >= 0; i-- {

2827 if releaseErr := vm.xdotool("keyup", pressed[i]); releaseErr != nil {

2828 err = errors.Join(err, releaseErr)

2829 }

2830 }

2831 }()

2832 for _, key := range keys {

2833 normalized := normalizeKey(key)

2834 pressed = append(pressed, normalized)

2835 if err = vm.xdotool("keydown", normalized); err != nil {

2836 return err

2837 }

2838 }

2839 return operation()

2840}

2841 

2842func handleComputerActions(vm *VM, actions responses.ComputerActionList) error {

2843 for _, action := range actions {

2844 var operation func() error

2845 switch action.Type {

2846 case "click":

2847 button, err := normalizeButton(action.Button)

2848 if err != nil {

2849 return err

2850 }

2851 operation = func() error {

2852 return vm.xdotool("mousemove", "--sync", fmt.Sprint(action.X), fmt.Sprint(action.Y), "click", fmt.Sprint(button))

2853 }

2854 case "double_click":

2855 operation = func() error {

2856 return vm.xdotool(

2857 "mousemove", "--sync", fmt.Sprint(action.X), fmt.Sprint(action.Y),

2858 "click", "--repeat", "2", "--delay", "100", "1",

2859 )

2860 }

2861 case "move":

2862 operation = func() error { return vm.xdotool("mousemove", "--sync", fmt.Sprint(action.X), fmt.Sprint(action.Y)) }

2863 case "drag":

2864 path := normalizeDragPath(action.Path)

2865 if len(path) < 2 {

2866 return &InvalidInputError{"Drag requires at least two points"}

2867 }

2868 operation = func() (err error) {

2869 if err = vm.xdotool("mousemove", "--sync", fmt.Sprint(path[0][0]), fmt.Sprint(path[0][1])); err != nil {

2870 return err

2871 }

2872 defer func() { err = errors.Join(err, vm.xdotool("mouseup", "1")) }()

2873 if err = vm.xdotool("mousedown", "1"); err != nil {

2874 return err

2875 }

2876 for _, point := range path[1:] {

2877 if err = vm.xdotool("mousemove", "--sync", fmt.Sprint(point[0]), fmt.Sprint(point[1])); err != nil {

2878 return err

2879 }

2880 }

2881 return nil

2882 }

2883 case "scroll":

2884 operation = func() error {

2885 if err := vm.xdotool("mousemove", "--sync", fmt.Sprint(action.X), fmt.Sprint(action.Y)); err != nil {

2886 return err

2887 }

2888 for _, button := range scrollButtons(action.ScrollX, action.ScrollY) {

2889 if err := vm.xdotool("click", fmt.Sprint(button)); err != nil {

2890 return err

2891 }

2892 }

2893 return nil

2894 }

2895 case "keypress":

2896 if len(action.Keys) == 0 {

2897 return &InvalidInputError{"Keypress requires keys"}

2898 }

2899 // Keydown/up provides finally-based release for combinations, too.

2900 if err := withModifiers(vm, action.Keys, func() error { return nil }); err != nil {

2901 return err

2902 }

2903 continue

2904 case "type":

2905 if err := vm.xdotool("type", "--clearmodifiers", "--", action.Text); err != nil {

2906 return err

2907 }

2908 continue

2909 case "wait":

2910 time.Sleep(2 * time.Second)

2911 continue

2912 case "screenshot":

2913 // The caller captures once after the batch, including screenshot-only batches.

2914 continue

2915 default:

2916 return &InvalidInputError{"Unsupported computer action: " + action.Type}

2917 }

2918 if len(action.Keys) != 0 {

2919 return &InvalidInputError{"Use the modifier-aware handler"}

2920 }

2921 if err := operation(); err != nil {

2922 return err

2923 }

2924 }

2925 return nil

2926}

2927```

2928 

1948```java2929```java

1949import com.openai.core.ObjectMappers;2930import com.openai.core.ObjectMappers;

1950import com.openai.models.responses.ComputerAction;2931import com.openai.models.responses.ComputerAction;


2055}3036}

2056```3037```

2057 3038 

3039```csharp

3040using System;

3041using System.Collections.Generic;

3042using System.Diagnostics;

3043using System.Globalization;

3044using System.IO;

3045using System.Linq;

3046using System.Runtime.ExceptionServices;

3047using System.Text;

3048using System.Text.Json;

3049using System.Text.Json.Serialization;

3050using System.Threading;

3051using System.Threading.Tasks;

3052 

3053// Application-owned host messages, independent of the OpenAI SDK computer-tool surface.

3054internal sealed record ComputerAction

3055{

3056 [JsonPropertyName("type")]

3057 public required string Type { get; init; }

3058 [JsonPropertyName("button")]

3059 public string Button { get; init; } = "";

3060 [JsonPropertyName("x")]

3061 public long X { get; init; }

3062 [JsonPropertyName("y")]

3063 public long Y { get; init; }

3064 [JsonPropertyName("keys")]

3065 public string[] Keys { get; init; } = [];

3066 [JsonPropertyName("path")]

3067 public Point[] Path { get; init; } = [];

3068 [JsonPropertyName("scroll_x")]

3069 public long ScrollX { get; init; }

3070 [JsonPropertyName("scroll_y")]

3071 public long ScrollY { get; init; }

3072 [JsonPropertyName("text")]

3073 public string Text { get; init; } = "";

3074}

3075 

3076internal static async Task WithModifiersAsync(VM vm, IReadOnlyList<string> keys, Func<Task> operation)

3077{

3078 List<string> pressed = [];

3079 List<Exception> failures = [];

3080 try

3081 {

3082 foreach (string key in keys)

3083 {

3084 string normalized = NormalizeKey(key);

3085 // A failed process may already have sent the keydown; release that key, too.

3086 pressed.Add(normalized);

3087 await XdotoolAsync(vm, "keydown", normalized);

3088 }

3089 await operation();

3090 }

3091 catch (Exception error)

3092 {

3093 failures.Add(error);

3094 }

3095 finally

3096 {

3097 for (int index = pressed.Count - 1; index >= 0; index--)

3098 {

3099 try

3100 {

3101 await XdotoolAsync(vm, "keyup", pressed[index]);

3102 }

3103 catch (Exception error)

3104 {

3105 failures.Add(error);

3106 }

3107 }

3108 }

3109 if (failures.Count == 1)

3110 {

3111 ExceptionDispatchInfo.Capture(failures[0]).Throw();

3112 }

3113 if (failures.Count > 1)

3114 {

3115 throw new AggregateException(failures);

3116 }

3117}

3118 

3119internal static async Task HandleComputerActionsAsync(VM vm, IReadOnlyList<ComputerAction> actions)

3120{

3121 foreach (ComputerAction action in actions)

3122 {

3123 Func<Task> operation;

3124 switch (action.Type)

3125 {

3126 case "click":

3127 int button = NormalizeButton(action.Button);

3128 operation = () => XdotoolAsync(

3129 vm,

3130 "mousemove",

3131 "--sync",

3132 Number(action.X),

3133 Number(action.Y),

3134 "click",

3135 Number(button));

3136 break;

3137 case "double_click":

3138 operation = () => XdotoolAsync(

3139 vm,

3140 "mousemove",

3141 "--sync",

3142 Number(action.X),

3143 Number(action.Y),

3144 "click",

3145 "--repeat",

3146 "2",

3147 "--delay",

3148 "100",

3149 "1");

3150 break;

3151 case "move":

3152 operation = () => XdotoolAsync(vm, "mousemove", "--sync", Number(action.X), Number(action.Y));

3153 break;

3154 case "drag":

3155 long[][] path = NormalizeDragPath(action.Path);

3156 if (path.Length < 2)

3157 {

3158 throw new ArgumentException("Drag requires at least two points.", nameof(actions));

3159 }

3160 operation = async () =>

3161 {

3162 await XdotoolAsync(vm, "mousemove", "--sync", Number(path[0][0]), Number(path[0][1]));

3163 Exception? primaryFailure = null;

3164 try

3165 {

3166 await XdotoolAsync(vm, "mousedown", "1");

3167 foreach (long[] point in path.Skip(1))

3168 {

3169 await XdotoolAsync(vm, "mousemove", "--sync", Number(point[0]), Number(point[1]));

3170 }

3171 }

3172 catch (Exception error)

3173 {

3174 primaryFailure = error;

3175 }

3176 finally

3177 {

3178 try

3179 {

3180 await XdotoolAsync(vm, "mouseup", "1");

3181 }

3182 catch (Exception releaseFailure)

3183 {

3184 primaryFailure = primaryFailure is null

3185 ? releaseFailure

3186 : new AggregateException(primaryFailure, releaseFailure);

3187 }

3188 }

3189 if (primaryFailure is not null)

3190 {

3191 ExceptionDispatchInfo.Capture(primaryFailure).Throw();

3192 }

3193 };

3194 break;

3195 case "scroll":

3196 operation = async () =>

3197 {

3198 await XdotoolAsync(vm, "mousemove", "--sync", Number(action.X), Number(action.Y));

3199 foreach (int scrollButton in ScrollButtons(action.ScrollX, action.ScrollY))

3200 {

3201 await XdotoolAsync(vm, "click", Number(scrollButton));

3202 }

3203 };

3204 break;

3205 case "keypress":

3206 if (action.Keys.Length == 0)

3207 {

3208 throw new ArgumentException("Keypress requires keys.", nameof(actions));

3209 }

3210 await WithModifiersAsync(vm, action.Keys, () => Task.CompletedTask);

3211 continue;

3212 case "type":

3213 await XdotoolAsync(vm, "type", "--clearmodifiers", "--", action.Text);

3214 continue;

3215 case "wait":

3216 await Task.Delay(TimeSpan.FromSeconds(2));

3217 continue;

3218 case "screenshot":

3219 // Capture once after the action batch, in the caller.

3220 continue;

3221 default:

3222 throw new ArgumentException($"Unsupported computer action: {action.Type}", nameof(actions));

3223 }

3224 if (action.Keys.Length != 0)

3225 {

3226 throw new ArgumentException("Use the modifier-aware handler.", nameof(actions));

3227 }

3228 await operation();

3229 }

3230}

3231 

3232private static string Number(long value) => value.ToString(CultureInfo.InvariantCulture);

3233```

3234 

2058```ruby3235```ruby

2059def run_xdotool(vm, *args)3236def run_xdotool(vm, *args)

2060 docker_exec(vm.container_name, "xdotool", args, env: { "DISPLAY" => vm.display })3237 docker_exec(vm.container_name, "xdotool", args, env: { "DISPLAY" => vm.display })


2323 ),3500 ),

2324 )3501 )

2325 case "keypress":3502 case "keypress":

2326 page.keyboard.press("+".join(normalize_key(key) for key in action.keys))3503 page.keyboard.press("+".join(normalize_key(key) for key in action.keys))

3504 case "type":

3505 page.keyboard.type(action.text)

3506 case "wait":

3507 time.sleep(2)

3508 case "screenshot":

3509 # The caller captures a screenshot after every action.

3510 continue

3511 case _:

3512 raise ValueError(f"Unsupported action: {action.type}")

3513```

3514 

3515```go

3516import (

3517 "errors"

3518 "fmt"

3519 "strings"

3520 "time"

3521 

3522 "github.com/openai/openai-go/v3/responses"

3523 "github.com/playwright-community/playwright-go"

3524)

3525 

3526func normalizeKey(key string) string {

3527 switch key {

3528 case "ENTER", "RETURN":

3529 return "Enter"

3530 case "ESC", "ESCAPE":

3531 return "Escape"

3532 case "TAB":

3533 return "Tab"

3534 case "SPACE":

3535 return "Space"

3536 case "BACKSPACE":

3537 return "Backspace"

3538 case "DELETE", "DEL":

3539 return "Delete"

3540 case "HOME":

3541 return "Home"

3542 case "END":

3543 return "End"

3544 case "PAGEUP":

3545 return "PageUp"

3546 case "PAGEDOWN":

3547 return "PageDown"

3548 case "UP", "ARROWUP":

3549 return "ArrowUp"

3550 case "DOWN", "ARROWDOWN":

3551 return "ArrowDown"

3552 case "LEFT", "ARROWLEFT":

3553 return "ArrowLeft"

3554 case "RIGHT", "ARROWRIGHT":

3555 return "ArrowRight"

3556 case "CTRL", "CONTROL":

3557 return "Control"

3558 case "SHIFT":

3559 return "Shift"

3560 case "ALT", "OPTION":

3561 return "Alt"

3562 case "META", "CMD", "COMMAND":

3563 return "Meta"

3564 default:

3565 return key

3566 }

3567}

3568 

3569func normalizeButton(button string) (playwright.MouseButton, error) {

3570 switch button {

3571 case "left":

3572 return playwright.MouseButton("left"), nil

3573 case "wheel":

3574 return playwright.MouseButton("middle"), nil

3575 case "right":

3576 return playwright.MouseButton("right"), nil

3577 default:

3578 return "", fmt.Errorf("unsupported mouse button: %s", button)

3579 }

3580}

3581 

3582func normalizeDragPath(path []responses.ComputerActionDragPath) [][2]int64 {

3583 result := make([][2]int64, len(path))

3584 for i, point := range path {

3585 result[i] = [2]int64{point.X, point.Y}

3586 }

3587 return result

3588}

3589 

3590// withModifiers releases every successfully pressed key, even after an error.

3591func withModifiers(page playwright.Page, keys []string, operation func() error) (err error) {

3592 pressed := make([]string, 0, len(keys))

3593 defer func() {

3594 for i := len(pressed) - 1; i >= 0; i-- {

3595 err = errors.Join(err, page.Keyboard().Up(pressed[i]))

3596 }

3597 }()

3598 for _, key := range keys {

3599 key = normalizeKey(key)

3600 if err = page.Keyboard().Down(key); err != nil {

3601 return err

3602 }

3603 pressed = append(pressed, key)

3604 }

3605 return operation()

3606}

3607 

3608func handleComputerActions(page playwright.Page, actions []responses.ComputerActionUnion) error {

3609 for _, action := range actions {

3610 var operation func() error

3611 switch action.Type {

3612 case "click":

3613 button, err := normalizeButton(action.Button)

3614 if err != nil {

3615 return err

3616 }

3617 operation = func() error {

3618 return page.Mouse().Click(

3619 float64(action.X), float64(action.Y),

3620 playwright.MouseClickOptions{Button: &button},

3621 )

3622 }

3623 case "double_click":

3624 operation = func() error {

3625 return page.Mouse().Dblclick(float64(action.X), float64(action.Y))

3626 }

3627 case "move":

3628 operation = func() error {

3629 return page.Mouse().Move(float64(action.X), float64(action.Y))

3630 }

3631 case "drag":

3632 path := normalizeDragPath(action.Path)

3633 if len(path) < 2 {

3634 return fmt.Errorf("drag requires at least two points")

3635 }

3636 operation = func() (err error) {

3637 if err = page.Mouse().Move(float64(path[0][0]), float64(path[0][1])); err != nil {

3638 return err

3639 }

3640 if err = page.Mouse().Down(); err != nil {

3641 return err

3642 }

3643 defer func() { err = errors.Join(err, page.Mouse().Up()) }()

3644 for _, point := range path[1:] {

3645 if err = page.Mouse().Move(float64(point[0]), float64(point[1])); err != nil {

3646 return err

3647 }

3648 }

3649 return nil

3650 }

3651 case "scroll":

3652 operation = func() error {

3653 if err := page.Mouse().Move(float64(action.X), float64(action.Y)); err != nil {

3654 return err

3655 }

3656 return page.Mouse().Wheel(float64(action.ScrollX), float64(action.ScrollY))

3657 }

3658 case "keypress":

3659 keys := make([]string, len(action.Keys))

3660 for i, key := range action.Keys {

3661 keys[i] = normalizeKey(key)

3662 }

3663 if len(keys) == 0 {

3664 return fmt.Errorf("keypress requires at least one key")

3665 }

3666 if err := page.Keyboard().Press(strings.Join(keys, "+")); err != nil {

3667 return err

3668 }

3669 continue

2327 case "type":3670 case "type":

2328 page.keyboard.type(action.text)3671 if err := page.Keyboard().InsertText(action.Text); err != nil {

3672 return err

3673 }

3674 continue

2329 case "wait":3675 case "wait":

2330 time.sleep(2)3676 time.Sleep(2 * time.Second)

2331 case "screenshot":

2332 # The caller captures a screenshot after every action.

2333 continue3677 continue

2334 case _:3678 case "screenshot":

2335 raise ValueError(f"Unsupported action: {action.type}")3679 continue // The caller captures the page after the batch.

3680 default:

3681 return fmt.Errorf("unsupported computer action: %s", action.Type)

3682 }

3683 if err := withModifiers(page, action.Keys, operation); err != nil {

3684 return err

3685 }

3686 }

3687 return nil

3688}

2336```3689```

2337 3690 

2338```java3691```java


2429}3782}

2430```3783```

2431 3784 

3785```csharp

3786using System;

3787using System.Collections.Generic;

3788using System.Diagnostics;

3789using System.IO;

3790using System.Linq;

3791using System.Runtime.ExceptionServices;

3792using System.Text.Json;

3793using System.Threading;

3794using System.Threading.Tasks;

3795using Microsoft.Playwright;

3796 

3797internal static string NormalizeKey(string key) => key switch

3798{

3799 "ENTER" or "RETURN" => "Enter",

3800 "ESC" or "ESCAPE" => "Escape",

3801 "TAB" => "Tab",

3802 "SPACE" => "Space",

3803 "BACKSPACE" => "Backspace",

3804 "DELETE" or "DEL" => "Delete",

3805 "HOME" => "Home",

3806 "END" => "End",

3807 "PAGEUP" => "PageUp",

3808 "PAGEDOWN" => "PageDown",

3809 "UP" or "ARROWUP" => "ArrowUp",

3810 "DOWN" or "ARROWDOWN" => "ArrowDown",

3811 "LEFT" or "ARROWLEFT" => "ArrowLeft",

3812 "RIGHT" or "ARROWRIGHT" => "ArrowRight",

3813 "CTRL" or "CONTROL" => "Control",

3814 "SHIFT" => "Shift",

3815 "ALT" or "OPTION" => "Alt",

3816 "META" or "CMD" or "COMMAND" => "Meta",

3817 _ => key,

3818};

3819 

3820internal static MouseButton NormalizeButton(string button) => button switch

3821{

3822 "left" => MouseButton.Left,

3823 "wheel" => MouseButton.Middle,

3824 "right" => MouseButton.Right,

3825 _ => throw new ArgumentException($"Unsupported mouse button: {button}", nameof(button)),

3826};

3827 

3828internal static long[][] NormalizeDragPath(JsonElement path) => path.EnumerateArray()

3829 .Select(point => new[] { point.GetProperty("x").GetInt64(), point.GetProperty("y").GetInt64() })

3830 .ToArray();

3831 

3832internal static async Task WithModifiersAsync(IPage page, IReadOnlyList<string> keys, Func<Task> operation)

3833{

3834 List<string> pressed = [];

3835 List<Exception> failures = [];

3836 try

3837 {

3838 foreach (string key in keys)

3839 {

3840 string normalized = NormalizeKey(key);

3841 await page.Keyboard.DownAsync(normalized);

3842 pressed.Add(normalized);

3843 }

3844 await operation();

3845 }

3846 catch (Exception error)

3847 {

3848 failures.Add(error);

3849 }

3850 finally

3851 {

3852 // Attempt every release, preserving both operation and cleanup errors.

3853 for (int i = pressed.Count - 1; i >= 0; i--)

3854 {

3855 try { await page.Keyboard.UpAsync(pressed[i]); }

3856 catch (Exception error) { failures.Add(error); }

3857 }

3858 }

3859 if (failures.Count != 0) throw new AggregateException(failures);

3860}

3861 

3862// These JSON actions are application inputs, not missing OpenAI SDK types.

3863internal static async Task HandleComputerActionsAsync(IPage page, IEnumerable<JsonElement> actions)

3864{

3865 foreach (JsonElement action in actions)

3866 {

3867 string type = action.GetProperty("type").GetString()

3868 ?? throw new ArgumentException("Action type is required.");

3869 string[] keys = action.TryGetProperty("keys", out JsonElement keyValues)

3870 && keyValues.ValueKind != JsonValueKind.Null

3871 ? keyValues.EnumerateArray().Select(key => key.GetString()

3872 ?? throw new ArgumentException("Keys must be strings.")).ToArray() : [];

3873 Func<Task> operation;

3874 switch (type)

3875 {

3876 case "click":

3877 MouseButton button = NormalizeButton(action.GetProperty("button").GetString()

3878 ?? throw new ArgumentException("Button is required."));

3879 operation = () => page.Mouse.ClickAsync(action.GetProperty("x").GetInt64(),

3880 action.GetProperty("y").GetInt64(), new() { Button = button });

3881 break;

3882 case "double_click":

3883 operation = () => page.Mouse.DblClickAsync(

3884 action.GetProperty("x").GetInt64(),

3885 action.GetProperty("y").GetInt64());

3886 break;

3887 case "move":

3888 operation = () => page.Mouse.MoveAsync(

3889 action.GetProperty("x").GetInt64(),

3890 action.GetProperty("y").GetInt64());

3891 break;

3892 case "drag":

3893 long[][] path = NormalizeDragPath(action.GetProperty("path"));

3894 if (path.Length < 2) throw new ArgumentException("Drag requires at least two points.");

3895 operation = async () =>

3896 {

3897 await page.Mouse.MoveAsync(path[0][0], path[0][1]);

3898 await page.Mouse.DownAsync();

3899 Exception? operationError = null;

3900 try

3901 {

3902 foreach (long[] point in path.Skip(1)) await page.Mouse.MoveAsync(point[0], point[1]);

3903 }

3904 catch (Exception error)

3905 {

3906 operationError = error;

3907 }

3908 finally

3909 {

3910 try { await page.Mouse.UpAsync(); }

3911 catch (Exception releaseError)

3912 {

3913 operationError = operationError is null

3914 ? releaseError : new AggregateException(operationError, releaseError);

3915 }

3916 }

3917 if (operationError is not null) ExceptionDispatchInfo.Capture(operationError).Throw();

3918 };

3919 break;

3920 case "scroll":

3921 operation = async () =>

3922 {

3923 await page.Mouse.MoveAsync(

3924 action.GetProperty("x").GetInt64(),

3925 action.GetProperty("y").GetInt64());

3926 await page.Mouse.WheelAsync(

3927 action.GetProperty("scroll_x").GetInt64(),

3928 action.GetProperty("scroll_y").GetInt64());

3929 };

3930 break;

3931 case "keypress":

3932 if (keys.Length == 0) throw new ArgumentException("Keypress requires at least one key.");

3933 await page.Keyboard.PressAsync(string.Join("+", keys.Select(NormalizeKey)));

3934 continue;

3935 case "type":

3936 await page.Keyboard.InsertTextAsync(action.GetProperty("text").GetString()

3937 ?? throw new ArgumentException("Text is required."));

3938 continue;

3939 case "wait":

3940 await Task.Delay(TimeSpan.FromSeconds(2));

3941 continue;

3942 case "screenshot":

3943 continue; // The caller captures the page after the batch.

3944 default:

3945 throw new ArgumentException($"Unsupported computer action: {type}");

3946 }

3947 await WithModifiersAsync(page, keys, operation);

3948 }

3949}

3950```

3951 

2432```ruby3952```ruby

2433def with_modifiers(page, keys)3953def with_modifiers(page, keys)

2434 pressed = []3954 pressed = []


2753 raise ValueError(f"Unsupported action: {action.type}")4273 raise ValueError(f"Unsupported action: {action.type}")

2754```4274```

2755 4275 

4276```go

4277import (

4278 "errors"

4279 "fmt"

4280 "github.com/openai/openai-go/v3/responses"

4281 "time"

4282)

4283 

4284func withModifiers(vm *VM, keys []string, operation func() error) (err error) {

4285 pressed := []string{}

4286 defer func() {

4287 // Attempt every release even if one release fails, retaining the original failure.

4288 for i := len(pressed) - 1; i >= 0; i-- {

4289 if releaseErr := vm.xdotool("keyup", pressed[i]); releaseErr != nil {

4290 err = errors.Join(err, releaseErr)

4291 }

4292 }

4293 }()

4294 for _, key := range keys {

4295 normalized := normalizeKey(key)

4296 pressed = append(pressed, normalized)

4297 if err = vm.xdotool("keydown", normalized); err != nil {

4298 return err

4299 }

4300 }

4301 return operation()

4302}

4303 

4304func handleComputerActions(vm *VM, actions responses.ComputerActionList) error {

4305 for _, action := range actions {

4306 var operation func() error

4307 switch action.Type {

4308 case "click":

4309 button, err := normalizeButton(action.Button)

4310 if err != nil {

4311 return err

4312 }

4313 operation = func() error {

4314 return vm.xdotool("mousemove", "--sync", fmt.Sprint(action.X), fmt.Sprint(action.Y), "click", fmt.Sprint(button))

4315 }

4316 case "double_click":

4317 operation = func() error {

4318 return vm.xdotool(

4319 "mousemove", "--sync", fmt.Sprint(action.X), fmt.Sprint(action.Y),

4320 "click", "--repeat", "2", "--delay", "100", "1",

4321 )

4322 }

4323 case "move":

4324 operation = func() error { return vm.xdotool("mousemove", "--sync", fmt.Sprint(action.X), fmt.Sprint(action.Y)) }

4325 case "drag":

4326 path := normalizeDragPath(action.Path)

4327 if len(path) < 2 {

4328 return &InvalidInputError{"Drag requires at least two points"}

4329 }

4330 operation = func() (err error) {

4331 if err = vm.xdotool("mousemove", "--sync", fmt.Sprint(path[0][0]), fmt.Sprint(path[0][1])); err != nil {

4332 return err

4333 }

4334 defer func() { err = errors.Join(err, vm.xdotool("mouseup", "1")) }()

4335 if err = vm.xdotool("mousedown", "1"); err != nil {

4336 return err

4337 }

4338 for _, point := range path[1:] {

4339 if err = vm.xdotool("mousemove", "--sync", fmt.Sprint(point[0]), fmt.Sprint(point[1])); err != nil {

4340 return err

4341 }

4342 }

4343 return nil

4344 }

4345 case "scroll":

4346 operation = func() error {

4347 if err := vm.xdotool("mousemove", "--sync", fmt.Sprint(action.X), fmt.Sprint(action.Y)); err != nil {

4348 return err

4349 }

4350 for _, button := range scrollButtons(action.ScrollX, action.ScrollY) {

4351 if err := vm.xdotool("click", fmt.Sprint(button)); err != nil {

4352 return err

4353 }

4354 }

4355 return nil

4356 }

4357 case "keypress":

4358 if len(action.Keys) == 0 {

4359 return &InvalidInputError{"Keypress requires keys"}

4360 }

4361 // Keydown/up provides finally-based release for combinations, too.

4362 if err := withModifiers(vm, action.Keys, func() error { return nil }); err != nil {

4363 return err

4364 }

4365 continue

4366 case "type":

4367 if err := vm.xdotool("type", "--clearmodifiers", "--", action.Text); err != nil {

4368 return err

4369 }

4370 continue

4371 case "wait":

4372 time.Sleep(2 * time.Second)

4373 continue

4374 case "screenshot":

4375 // The caller captures once after the batch, including screenshot-only batches.

4376 continue

4377 default:

4378 return &InvalidInputError{"Unsupported computer action: " + action.Type}

4379 }

4380 if err := withModifiers(vm, action.Keys, operation); err != nil {

4381 return err

4382 }

4383 }

4384 return nil

4385}

4386```

4387 

2756```java4388```java

2757import com.openai.core.ObjectMappers;4389import com.openai.core.ObjectMappers;

2758import com.openai.models.responses.ComputerAction;4390import com.openai.models.responses.ComputerAction;


2877}4509}

2878```4510```

2879 4511 

4512```csharp

4513using System;

4514using System.Collections.Generic;

4515using System.Diagnostics;

4516using System.Globalization;

4517using System.IO;

4518using System.Linq;

4519using System.Runtime.ExceptionServices;

4520using System.Text;

4521using System.Text.Json;

4522using System.Text.Json.Serialization;

4523using System.Threading;

4524using System.Threading.Tasks;

4525 

4526// Application-owned host messages, independent of the OpenAI SDK computer-tool surface.

4527internal sealed record ComputerAction

4528{

4529 [JsonPropertyName("type")]

4530 public required string Type { get; init; }

4531 [JsonPropertyName("button")]

4532 public string Button { get; init; } = "";

4533 [JsonPropertyName("x")]

4534 public long X { get; init; }

4535 [JsonPropertyName("y")]

4536 public long Y { get; init; }

4537 [JsonPropertyName("keys")]

4538 public string[] Keys { get; init; } = [];

4539 [JsonPropertyName("path")]

4540 public Point[] Path { get; init; } = [];

4541 [JsonPropertyName("scroll_x")]

4542 public long ScrollX { get; init; }

4543 [JsonPropertyName("scroll_y")]

4544 public long ScrollY { get; init; }

4545 [JsonPropertyName("text")]

4546 public string Text { get; init; } = "";

4547}

4548 

4549internal static async Task WithModifiersAsync(VM vm, IReadOnlyList<string> keys, Func<Task> operation)

4550{

4551 List<string> pressed = [];

4552 List<Exception> failures = [];

4553 try

4554 {

4555 foreach (string key in keys)

4556 {

4557 string normalized = NormalizeKey(key);

4558 // A failed process may already have sent the keydown; release that key, too.

4559 pressed.Add(normalized);

4560 await XdotoolAsync(vm, "keydown", normalized);

4561 }

4562 await operation();

4563 }

4564 catch (Exception error)

4565 {

4566 failures.Add(error);

4567 }

4568 finally

4569 {

4570 for (int index = pressed.Count - 1; index >= 0; index--)

4571 {

4572 try

4573 {

4574 await XdotoolAsync(vm, "keyup", pressed[index]);

4575 }

4576 catch (Exception error)

4577 {

4578 failures.Add(error);

4579 }

4580 }

4581 }

4582 if (failures.Count == 1)

4583 {

4584 ExceptionDispatchInfo.Capture(failures[0]).Throw();

4585 }

4586 if (failures.Count > 1)

4587 {

4588 throw new AggregateException(failures);

4589 }

4590}

4591 

4592internal static async Task HandleComputerActionsAsync(VM vm, IReadOnlyList<ComputerAction> actions)

4593{

4594 foreach (ComputerAction action in actions)

4595 {

4596 Func<Task> operation;

4597 switch (action.Type)

4598 {

4599 case "click":

4600 int button = NormalizeButton(action.Button);

4601 operation = () => XdotoolAsync(

4602 vm,

4603 "mousemove",

4604 "--sync",

4605 Number(action.X),

4606 Number(action.Y),

4607 "click",

4608 Number(button));

4609 break;

4610 case "double_click":

4611 operation = () => XdotoolAsync(

4612 vm,

4613 "mousemove",

4614 "--sync",

4615 Number(action.X),

4616 Number(action.Y),

4617 "click",

4618 "--repeat",

4619 "2",

4620 "--delay",

4621 "100",

4622 "1");

4623 break;

4624 case "move":

4625 operation = () => XdotoolAsync(vm, "mousemove", "--sync", Number(action.X), Number(action.Y));

4626 break;

4627 case "drag":

4628 long[][] path = NormalizeDragPath(action.Path);

4629 if (path.Length < 2)

4630 {

4631 throw new ArgumentException("Drag requires at least two points.", nameof(actions));

4632 }

4633 operation = async () =>

4634 {

4635 await XdotoolAsync(vm, "mousemove", "--sync", Number(path[0][0]), Number(path[0][1]));

4636 Exception? primaryFailure = null;

4637 try

4638 {

4639 await XdotoolAsync(vm, "mousedown", "1");

4640 foreach (long[] point in path.Skip(1))

4641 {

4642 await XdotoolAsync(vm, "mousemove", "--sync", Number(point[0]), Number(point[1]));

4643 }

4644 }

4645 catch (Exception error)

4646 {

4647 primaryFailure = error;

4648 }

4649 finally

4650 {

4651 try

4652 {

4653 await XdotoolAsync(vm, "mouseup", "1");

4654 }

4655 catch (Exception releaseFailure)

4656 {

4657 primaryFailure = primaryFailure is null

4658 ? releaseFailure

4659 : new AggregateException(primaryFailure, releaseFailure);

4660 }

4661 }

4662 if (primaryFailure is not null)

4663 {

4664 ExceptionDispatchInfo.Capture(primaryFailure).Throw();

4665 }

4666 };

4667 break;

4668 case "scroll":

4669 operation = async () =>

4670 {

4671 await XdotoolAsync(vm, "mousemove", "--sync", Number(action.X), Number(action.Y));

4672 foreach (int scrollButton in ScrollButtons(action.ScrollX, action.ScrollY))

4673 {

4674 await XdotoolAsync(vm, "click", Number(scrollButton));

4675 }

4676 };

4677 break;

4678 case "keypress":

4679 if (action.Keys.Length == 0)

4680 {

4681 throw new ArgumentException("Keypress requires keys.", nameof(actions));

4682 }

4683 await WithModifiersAsync(vm, action.Keys, () => Task.CompletedTask);

4684 continue;

4685 case "type":

4686 await XdotoolAsync(vm, "type", "--clearmodifiers", "--", action.Text);

4687 continue;

4688 case "wait":

4689 await Task.Delay(TimeSpan.FromSeconds(2));

4690 continue;

4691 case "screenshot":

4692 // Capture once after the action batch, in the caller.

4693 continue;

4694 default:

4695 throw new ArgumentException($"Unsupported computer action: {action.Type}", nameof(actions));

4696 }

4697 await WithModifiersAsync(vm, action.Keys, operation);

4698 }

4699}

4700 

4701private static string Number(long value) => value.ToString(CultureInfo.InvariantCulture);

4702```

4703 

2880```ruby4704```ruby

2881def with_modifiers(vm, keys)4705def with_modifiers(vm, keys)

2882 pressed = []4706 pressed = []


3327 return page.screenshot(type="png")5151 return page.screenshot(type="png")

3328```5152```

3329 5153 

5154```go

5155import "github.com/playwright-community/playwright-go"

5156 

5157func captureScreenshot(page playwright.Page) ([]byte, error) {

5158 format := playwright.ScreenshotType("png")

5159 return page.Screenshot(playwright.PageScreenshotOptions{Type: &format})

5160}

5161```

5162 

3330```java5163```java

3331import com.microsoft.playwright.*;5164import com.microsoft.playwright.*;

3332import com.microsoft.playwright.options.*;5165import com.microsoft.playwright.options.*;


3341}5174}

3342```5175```

3343 5176 

5177```csharp

5178using System;

5179using System.Collections.Generic;

5180using System.IO;

5181using System.Text.Json;

5182using System.Threading;

5183using System.Threading.Tasks;

5184using Microsoft.Playwright;

5185 

5186internal static Task<byte[]> CaptureScreenshotAsync(IPage page) =>

5187 page.ScreenshotAsync(new() { Type = ScreenshotType.Png });

5188```

5189 

3344```ruby5190```ruby

3345def capture_screenshot(page)5191def capture_screenshot(page)

3346 page.screenshot(type: "png")5192 page.screenshot(type: "png")


3381 )5227 )

3382```5228```

3383 5229 

5230```go

5231import (

5232 "bytes"

5233 "fmt"

5234 "image/png"

5235)

5236 

5237func captureScreenshot(vm *VM) ([]byte, error) {

5238 data, err := vm.dockerExec(

5239 "import",

5240 []string{"-window", "root", "png:-"},

5241 map[string]string{"DISPLAY": vm.Display},

5242 )

5243 if err != nil {

5244 return nil, err

5245 }

5246 if _, err := png.DecodeConfig(bytes.NewReader(data)); err != nil {

5247 return nil, fmt.Errorf("invalid screenshot PNG: %w", err)

5248 }

5249 return data, nil

5250}

5251```

5252 

3384```java5253```java

3385import com.openai.core.ObjectMappers;5254import com.openai.core.ObjectMappers;

3386import java.nio.file.*;5255import java.nio.file.*;


3397}5266}

3398```5267```

3399 5268 

5269```csharp

5270using System;

5271using System.Collections.Generic;

5272using System.Diagnostics;

5273using System.IO;

5274using System.Text;

5275using System.Text.Json;

5276using System.Threading;

5277using System.Threading.Tasks;

5278 

5279internal static Task<byte[]> CaptureScreenshotAsync(VM vm) => DockerExecAsync(

5280 vm, "import", ["-window", "root", "png:-"],

5281 new Dictionary<string, string> { ["DISPLAY"] = vm.Display });

5282```

5283 

3400```ruby5284```ruby

3401def capture_screenshot(vm)5285def capture_screenshot(vm)

3402 docker_exec(5286 docker_exec(

Details

2113}2113}

2114```2114```

2115 2115 

2116```csharp

2117using System.Diagnostics;

2118using System.Globalization;

2119using System.Runtime.InteropServices;

2120using System.Text;

2121using System.Text.Json;

2122 

2123namespace OpenAI.Docs.Examples.Tools.ShellExecutor;

2124 

2125internal static class ShellExecutor

2126{

2127 internal static async Task RunAsync()

2128 {

2129 // Linux host with util-linux setsid and /bin/sh installed. Only run commands

2130 // approved by the application. Process groups are not a security sandbox.

2131 string[] arguments = Environment.GetCommandLineArgs().Skip(1).ToArray();

2132 // The project runner adds its selector before this sample's arguments.

2133 if (arguments is ["tools-shell-executor", ..])

2134 {

2135 arguments = arguments[1..];

2136 }

2137 if (arguments.Length > 2)

2138 {

2139 throw new ArgumentException("Expected [command] [timeoutSeconds].");

2140 }

2141 string command = arguments.Length > 0 ? arguments[0] : "printf shell-executor-ready";

2142 double timeoutSeconds = arguments.Length > 1

2143 ? double.Parse(arguments[1], CultureInfo.InvariantCulture) : 1.0;

2144 Console.WriteLine(JsonSerializer.Serialize(await ExecuteAsync(command, timeoutSeconds)));

2145 }

2146 internal static async Task<ShellResult> ExecuteAsync(string command, double timeoutSeconds = 1.0)

2147 {

2148 if (!OperatingSystem.IsLinux())

2149 {

2150 throw new PlatformNotSupportedException("This executor requires Linux process groups.");

2151 }

2152 ArgumentNullException.ThrowIfNull(command);

2153 if (!double.IsFinite(timeoutSeconds) || timeoutSeconds <= 0 || timeoutSeconds > 86400)

2154 {

2155 throw new ArgumentOutOfRangeException(nameof(timeoutSeconds), "Use 0 < timeout <= 86400 seconds.");

2156 }

2157 

2158 ProcessStartInfo start = new("setsid")

2159 {

2160 UseShellExecute = false,

2161 RedirectStandardInput = true,

2162 RedirectStandardOutput = true,

2163 RedirectStandardError = true,

2164 StandardOutputEncoding = Encoding.UTF8,

2165 StandardErrorEncoding = Encoding.UTF8,

2166 };

2167 // ArgumentList preserves the whole command, including shell quotes, as one argument.

2168 start.ArgumentList.Add("/bin/sh");

2169 start.ArgumentList.Add("-c");

2170 start.ArgumentList.Add(command);

2171 using Process process = Process.Start(start)

2172 ?? throw new InvalidOperationException("Unable to start setsid.");

2173 process.StandardInput.Close();

2174 

2175 TaskCompletionSource<bool> outputLimit = new(TaskCreationOptions.RunContinuationsAsynchronously);

2176 // Drain both pipes concurrently so a full stderr pipe cannot deadlock stdout.

2177 Task<string> stdout = DrainAsync(process.StandardOutput, outputLimit);

2178 Task<string> stderr = DrainAsync(process.StandardError, outputLimit);

2179 Task exited = process.WaitForExitAsync();

2180 Task finished = Task.WhenAll(exited, stdout, stderr);

2181 using CancellationTokenSource deadlineCancellation = new();

2182 Task deadline = Task.Delay(TimeSpan.FromSeconds(timeoutSeconds), deadlineCancellation.Token);

2183 bool timedOut;

2184 bool exceededOutput;

2185 try

2186 {

2187 Task winner = await Task.WhenAny(finished, deadline, outputLimit.Task);

2188 timedOut = winner == deadline;

2189 exceededOutput = outputLimit.Task.IsCompleted;

2190 }

2191 finally

2192 {

2193 await deadlineCancellation.CancelAsync();

2194 // Clean up even when the shell exits first: descendants can retain its

2195 // pipes, or can close them and continue running in the background.

2196 // The process tree handles startup before setsid has created the group.

2197 try

2198 {

2199 if (!process.HasExited)

2200 {

2201 process.Kill(entireProcessTree: true);

2202 }

2203 }

2204 catch (InvalidOperationException) when (process.HasExited)

2205 {

2206 // The process exited between the check and Kill.

2207 }

2208 finally

2209 {

2210 KillGroup(process.Id);

2211 }

2212 await exited;

2213 }

2214 

2215 // A child deliberately creating another session escapes the owned group.

2216 // Bound pipe cleanup as well; use an OS sandbox for adversarial commands.

2217 try

2218 {

2219 await finished.WaitAsync(TimeSpan.FromSeconds(2));

2220 }

2221 catch (TimeoutException)

2222 {

2223 throw new IOException("A process outside the owned group retained an output pipe.");

2224 }

2225 return new ShellResult(await stdout, await stderr,

2226 timedOut ? -1 : exceededOutput ? 1 : process.ExitCode, timedOut);

2227 }

2228 

2229 private static async Task<string> DrainAsync(StreamReader reader, TaskCompletionSource<bool> limit)

2230 {

2231 const int maximumCharacters = 1024 * 1024;

2232 StringBuilder captured = new();

2233 char[] buffer = new char[4096];

2234 int count;

2235 while ((count = await reader.ReadAsync(buffer.AsMemory())) != 0)

2236 {

2237 int retained = Math.Min(count, maximumCharacters - captured.Length);

2238 captured.Append(buffer, 0, retained);

2239 if (retained != count)

2240 {

2241 limit.TrySetResult(true);

2242 }

2243 }

2244 return captured.ToString();

2245 }

2246 

2247 private static void KillGroup(int processId)

2248 {

2249 const int noSuchProcess = 3;

2250 if (Kill(-processId, 9) != 0)

2251 {

2252 int error = Marshal.GetLastPInvokeError();

2253 if (error != noSuchProcess)

2254 {

2255 throw new System.ComponentModel.Win32Exception(error, "Unable to terminate the owned process group.");

2256 }

2257 }

2258 }

2259 

2260 // DllImport keeps this standalone example usable without enabling unsafe compilation.

2261#pragma warning disable SYSLIB1054

2262 [DllImport("libc", EntryPoint = "kill", SetLastError = true)]

2263 private static extern int Kill(int processId, int signal);

2264#pragma warning restore SYSLIB1054

2265 

2266 internal sealed record ShellResult(

2267 [property: System.Text.Json.Serialization.JsonPropertyName("stdout")] string Stdout,

2268 [property: System.Text.Json.Serialization.JsonPropertyName("stderr")] string Stderr,

2269 [property: System.Text.Json.Serialization.JsonPropertyName("exit_code")] int ExitCode,

2270 [property: System.Text.Json.Serialization.JsonPropertyName("timed_out")] bool TimedOut);

2271}

2272```

2273 

2116```ruby2274```ruby

2117require "open3"2275require "open3"

2118 2276 

libraries.md +1 −1

Details

177<dependency>177<dependency>

178 <groupId>com.openai</groupId>178 <groupId>com.openai</groupId>

179 <artifactId>openai-java</artifactId>179 <artifactId>openai-java</artifactId>

180 <version>4.113.0</version>180 <version>4.114.0</version>

181</dependency>181</dependency>

182```182```

183 183 

quickstart.md +1 −1

Details

187<dependency>187<dependency>

188 <groupId>com.openai</groupId>188 <groupId>com.openai</groupId>

189 <artifactId>openai-java</artifactId>189 <artifactId>openai-java</artifactId>

190 <version>4.113.0</version>190 <version>4.114.0</version>

191</dependency>191</dependency>

192```192```

193 193 

Details

206}206}

207```207```

208 208 

209```csharp

210using System.Net;

211using System.Security.Cryptography;

212using System.Text;

213using System.Text.RegularExpressions;

214using HtmlAgilityPack;

215 

216// Paste the four C# steps into Program.cs in a .NET 10 console project.

217// Add the parser with: dotnet add package HtmlAgilityPack --version 1.11.71

218 

219const int MaxPages = 100;

220const int MaxRedirects = 5;

221const int MaxPageBytes = 1_048_576;

222const int MaxLinksPerPage = 2_000;

223 

224// Redirects are checked before sending another request. TLS uses normal OS trust.

225static HttpClient CreateClient() => new(new HttpClientHandler

226{

227 AllowAutoRedirect = false,

228 UseCookies = false,

229 AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate

230})

231{

232 Timeout = TimeSpan.FromSeconds(10)

233};

234```

235 

209```ruby236```ruby

210require "net/http"237require "net/http"

211require "uri"238require "uri"


453}480}

454```481```

455 482 

483```csharp

484static async Task<IReadOnlyList<string>> GetHyperlinksAsync(

485 HttpClient client, Uri url, HtmlDocument? fetchedDocument = null)

486{

487 // Reuse the already fetched HTML when calling this helper from a crawl.

488 if (fetchedDocument is not null) return Hyperlinks(fetchedDocument);

489 HtmlPage? page = await FetchHtmlAsync(client, url, url);

490 return page is null ? [] : Hyperlinks(page.Document);

491}

492 

493static string[] Hyperlinks(HtmlDocument document) =>

494 document.DocumentNode.Descendants("a")

495 .Where(node => node.Attributes["href"] is not null)

496 .Take(MaxLinksPerPage)

497 .Select(node => HtmlEntity.DeEntitize(node.GetAttributeValue("href", "")))

498 .ToArray();

499 

500static async Task<HtmlPage?> FetchHtmlAsync(

501 HttpClient client, Uri initial, Uri origin, HashSet<string>? fetched = null)

502{

503 Uri current = initial;

504 HashSet<string> redirects = new(StringComparer.Ordinal);

505 using CancellationTokenSource deadline = new(TimeSpan.FromSeconds(10));

506 for (int hop = 0; hop <= MaxRedirects; hop++)

507 {

508 if (!SameAuthority(origin, current))

509 {

510 Console.Error.WriteLine($"Skipping redirect outside the same-authority boundary: {current}");

511 return null;

512 }

513 if (!redirects.Add(current.AbsoluteUri))

514 {

515 Console.Error.WriteLine($"Skipping redirect loop: {current}");

516 return null;

517 }

518 // Shared across the traversal, so redirect targets are fetched only once.

519 if (fetched is not null && !fetched.Add(current.AbsoluteUri))

520 {

521 return null;

522 }

523 using HttpRequestMessage request = new(HttpMethod.Get, current);

524 using HttpResponseMessage response = await client.SendAsync(

525 request, HttpCompletionOption.ResponseHeadersRead, deadline.Token);

526 int status = (int)response.StatusCode;

527 if (status is 301 or 302 or 303 or 307 or 308)

528 {

529 Uri? location = response.Headers.Location;

530 Uri? target = location is null ? null : ResolveLink(current, location.OriginalString);

531 if (hop == MaxRedirects || target is null)

532 {

533 Console.Error.WriteLine($"Skipping invalid redirect or redirect limit: {current}");

534 return null;

535 }

536 current = target;

537 continue;

538 }

539 if (response.StatusCode != HttpStatusCode.OK)

540 {

541 Console.Error.WriteLine($"Skipping HTTP {status}: {current}");

542 return null;

543 }

544 if (!string.Equals(response.Content.Headers.ContentType?.MediaType,

545 "text/html", StringComparison.OrdinalIgnoreCase))

546 {

547 Console.Error.WriteLine($"Skipping non-HTML content: {current}");

548 return null;

549 }

550 if (response.Content.Headers.ContentLength is > MaxPageBytes)

551 {

552 throw new InvalidDataException($"HTML page exceeds {MaxPageBytes} bytes: {current}");

553 }

554 await using Stream input = await response.Content.ReadAsStreamAsync(deadline.Token);

555 using MemoryStream body = new();

556 byte[] buffer = new byte[8192];

557 int count;

558 while ((count = await input.ReadAsync(buffer.AsMemory(), deadline.Token)) != 0)

559 {

560 if (body.Length + count > MaxPageBytes)

561 {

562 throw new InvalidDataException($"HTML page exceeds {MaxPageBytes} bytes: {current}");

563 }

564 body.Write(buffer, 0, count);

565 }

566 string? charset = response.Content.Headers.ContentType?.CharSet?.Trim('"');

567 Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

568 Encoding encoding = string.IsNullOrWhiteSpace(charset) ? Encoding.UTF8 : Encoding.GetEncoding(charset);

569 body.Position = 0;

570 using StreamReader reader = new(body, encoding, detectEncodingFromByteOrderMarks: true);

571 HtmlDocument document = new();

572 document.LoadHtml(await reader.ReadToEndAsync(deadline.Token));

573 return new HtmlPage(current, document);

574 }

575 throw new InvalidOperationException("Unreachable redirect state.");

576}

577```

578 

456```ruby579```ruby

457def fetch_page(url, local_domain = nil)580def fetch_page(url, local_domain = nil)

458 uri = URI.parse(url)581 uri = URI.parse(url)


611}734}

612```735```

613 736 

737```csharp

738static async Task<IReadOnlyList<string>> GetDomainHyperlinksAsync(

739 HttpClient client, Uri origin, Uri url, IReadOnlyList<string>? fetchedHyperlinks = null)

740{

741 if (!SameAuthority(origin, url))

742 {

743 throw new ArgumentException("The page must have the same authority as the crawl origin.", nameof(url));

744 }

745 if (fetchedHyperlinks is not null)

746 return DomainHyperlinks(origin, url, fetchedHyperlinks).Select(link => link.AbsoluteUri).ToArray();

747 HtmlPage? page = await FetchHtmlAsync(client, url, origin);

748 return page is null ? [] : DomainHyperlinks(origin, page.Url, Hyperlinks(page.Document))

749 .Select(link => link.AbsoluteUri).ToArray();

750}

751 

752static List<Uri> DomainHyperlinks(Uri origin, Uri page, IEnumerable<string> hrefs)

753{

754 HashSet<string> seen = new(StringComparer.Ordinal);

755 List<Uri> links = [];

756 foreach (string href in hrefs)

757 {

758 string reference = href.Trim();

759 if (reference.Length == 0 || reference.StartsWith('#'))

760 {

761 continue;

762 }

763 Uri? link = ResolveLink(page, reference);

764 if (link is not null && SameAuthority(origin, link) && seen.Add(link.AbsoluteUri))

765 {

766 links.Add(link);

767 }

768 }

769 return links;

770}

771 

772static bool SameAuthority(Uri origin, Uri candidate) =>

773 candidate.IsAbsoluteUri && candidate.Scheme is "http" or "https"

774 && candidate.UserInfo.Length == 0

775 && string.Equals(origin.Authority, candidate.Authority, StringComparison.OrdinalIgnoreCase);

776 

777static Uri? ResolveLink(Uri page, string reference)

778{

779 // System.Uri preserves the current path for query-only references.

780 if (!Uri.TryCreate(page, reference, out Uri? resolved)

781 || resolved.Scheme is not ("http" or "https") || resolved.UserInfo.Length != 0)

782 {

783 return null;

784 }

785 // Slice the escaped absolute URI so query escapes keep their identity.

786 string absolute = resolved.AbsoluteUri;

787 int fragment = absolute.IndexOf('#', StringComparison.Ordinal);

788 return fragment < 0 ? resolved : new Uri(absolute[..fragment]);

789}

790```

791 

614```ruby792```ruby

615def get_domain_hyperlinks(local_domain, url)793def get_domain_hyperlinks(local_domain, url)

616 get_hyperlinks(url).filter_map do |link|794 get_hyperlinks(url).filter_map do |link|


1031}1209}

1032```1210```

1033 1211 

1212```csharp

1213// Replace this with a website you own or have permission to crawl.

1214Uri start = new("https://example.com/");

1215using HttpClient client = CreateClient();

1216IReadOnlyList<LinkObservation> observations = await CrawlAsync(client, start);

1217 

1218static async Task<IReadOnlyList<LinkObservation>> CrawlAsync(HttpClient client, Uri start)

1219{

1220 List<LinkObservation> observations = [];

1221 if (!SameAuthority(start, start))

1222 {

1223 throw new ArgumentException("Use an HTTP or HTTPS URL without embedded credentials.", nameof(start));

1224 }

1225 start = new UriBuilder(start) { Fragment = "" }.Uri;

1226 string directory = Path.Combine("text", OutputDirectoryName(start));

1227 Directory.CreateDirectory(directory);

1228 Directory.CreateDirectory("processed");

1229 Queue<Uri> queue = new();

1230 queue.Enqueue(start);

1231 HashSet<string> scheduled = new(StringComparer.Ordinal) { start.AbsoluteUri };

1232 HashSet<string> fetched = new(StringComparer.Ordinal);

1233 int saved = 0;

1234 while (queue.TryDequeue(out Uri? url))

1235 {

1236 HtmlPage? page = await FetchHtmlAsync(client, url, start, fetched);

1237 if (page is null)

1238 {

1239 continue;

1240 }

1241 // Redirect aliases can share a final page; FetchHtmlAsync deduplicates requests.

1242 string path = Path.Combine(directory, PageFilename(page.Url));

1243 await File.WriteAllTextAsync(path, VisibleText(page.Document.DocumentNode), new UTF8Encoding(false));

1244 Console.WriteLine(page.Url.AbsoluteUri);

1245 saved++;

1246 IReadOnlyList<string> hyperlinks = await GetHyperlinksAsync(client, page.Url, page.Document);

1247 IReadOnlyList<string> domainHyperlinks = await GetDomainHyperlinksAsync(client, start, page.Url, hyperlinks);

1248 observations.Add(new(page.Url, hyperlinks, domainHyperlinks));

1249 foreach (string address in domainHyperlinks)

1250 {

1251 Uri link = new(address);

1252 if (scheduled.Contains(link.AbsoluteUri))

1253 {

1254 continue;

1255 }

1256 if (scheduled.Count == MaxPages)

1257 {

1258 Console.Error.WriteLine($"Crawl limited to {MaxPages} scheduled pages.");

1259 break;

1260 }

1261 scheduled.Add(link.AbsoluteUri);

1262 queue.Enqueue(link);

1263 }

1264 }

1265 Console.Error.WriteLine($"Saved {saved} HTML pages.");

1266 return observations;

1267}

1268 

1269static string OutputDirectoryName(Uri origin)

1270{

1271 string host = origin.IdnHost;

1272 bool ordinaryHost = origin.IsDefaultPort && host.Length <= 200

1273 && host.All(character => char.IsAsciiLetterOrDigit(character) || character is '.' or '-')

1274 && !host.EndsWith('.')

1275 && !Regex.IsMatch(host, @"^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)",

1276 RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);

1277 // Keep the guide's text/example.com layout; ports, IPv6 and device names use ASCII.

1278 return ordinaryHost ? host : "site-" + Convert.ToHexString(

1279 SHA256.HashData(Encoding.UTF8.GetBytes(origin.Authority))).ToLowerInvariant();

1280}

1281 

1282static string PageFilename(Uri url)

1283{

1284 string digest = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(url.AbsoluteUri)))

1285 .ToLowerInvariant();

1286 string suffix = "#" + digest + ".txt";

1287 string readable = Uri.UnescapeDataString(url.Authority + url.AbsolutePath);

1288 StringBuilder prefix = new();

1289 int bytes = 0;

1290 // Windows reserves device basenames even before an extension, such as con.example.

1291 if (Regex.IsMatch(readable, @"^(con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³])(?:\.|$)",

1292 RegexOptions.IgnoreCase | RegexOptions.CultureInvariant))

1293 {

1294 prefix.Append('_');

1295 bytes++;

1296 }

1297 foreach (Rune rune in readable.EnumerateRunes())

1298 {

1299 bool invalid = rune.Value < 32 || rune.Value is '/' or '\\' or ':' or '*' or '?' or '"' or '<' or '>' or '|';

1300 string part = invalid ? "_" : rune.ToString();

1301 int length = Encoding.UTF8.GetByteCount(part);

1302 if (bytes + length > 255 - suffix.Length)

1303 {

1304 break;

1305 }

1306 prefix.Append(part);

1307 bytes += length;

1308 }

1309 return prefix.ToString() + suffix;

1310}

1311 

1312static string VisibleText(HtmlNode root)

1313{

1314 StringBuilder text = new();

1315 AppendText(root, text);

1316 return Regex.Replace(HtmlEntity.DeEntitize(text.ToString()), @"\s+", " ").Trim();

1317}

1318 

1319static void AppendText(HtmlNode node, StringBuilder text)

1320{

1321 if (node.Name is "script" or "style" || node.NodeType == HtmlNodeType.Comment)

1322 {

1323 return;

1324 }

1325 if (node.NodeType == HtmlNodeType.Text)

1326 {

1327 text.Append(node.InnerText);

1328 return;

1329 }

1330 bool block = node.Name is "address" or "article" or "aside" or "blockquote" or "br"

1331 or "dd" or "div" or "dl" or "dt" or "fieldset" or "figcaption" or "figure"

1332 or "footer" or "form" or "h1" or "h2" or "h3" or "h4" or "h5" or "h6"

1333 or "header" or "hr" or "li" or "main" or "nav" or "ol" or "p" or "pre"

1334 or "section" or "table" or "td" or "th" or "tr" or "ul";

1335 if (block) text.Append(' ');

1336 foreach (HtmlNode child in node.ChildNodes)

1337 {

1338 AppendText(child, text);

1339 }

1340 if (block) text.Append(' ');

1341}

1342internal sealed record LinkObservation(

1343 Uri Url, IReadOnlyList<string> Hyperlinks, IReadOnlyList<string> DomainHyperlinks);

1344 

1345sealed record HtmlPage(Uri Url, HtmlDocument Document);

1346```

1347 

1034```ruby1348```ruby

1035def crawl(full_url)1349def crawl(full_url)

1036 initial = URI.parse(full_url)1350 initial = URI.parse(full_url)


1164}1478}

1165```1479```

1166 1480 

1481```csharp

1482using System.Text.Json;

1483using System.Text.RegularExpressions;

1484 

1485namespace OpenAI.Docs.Examples.TutorialCrawlWebsiteEmbeddings.RemoveNewlines;

1486 

1487internal static class RemoveNewlinesSample

1488{

1489 

1490internal static void ShowExample()

1491 {

1492 Console.WriteLine(RemoveNewlines("first\nsecond"));

1493 }

1494 internal static string RemoveNewlines(string text)

1495 {

1496 ArgumentNullException.ThrowIfNull(text);

1497 return Regex.Replace(

1498 text.Replace("\r\n", " ", StringComparison.Ordinal)

1499 .Replace("\r", " ", StringComparison.Ordinal)

1500 .Replace("\n", " ", StringComparison.Ordinal)

1501 .Replace(@"\n", " ", StringComparison.Ordinal),

1502 " {2,}", " ");

1503 }

1504}

1505```

1506 

1167```ruby1507```ruby

1168def remove_newlines(texts)1508def remove_newlines(texts)

1169 texts.map { |text| text.tr("\n", " ").gsub('\n', " ").gsub(" ", " ").gsub(" ", " ") }1509 texts.map { |text| text.tr("\n", " ").gsub('\n', " ").gsub(" ", " ").gsub(" ", " ") }


1376}1716}

1377```1717```

1378 1718 

1719```csharp

1720using System;

1721using System.Collections.Generic;

1722using System.Globalization;

1723using System.IO;

1724using System.Linq;

1725using System.Security.Cryptography;

1726using System.Text;

1727using System.Text.Json;

1728using System.Text.RegularExpressions;

1729using System.Threading.Tasks;

1730 

1731// Use the same origin and working directory as the crawler.

1732Uri origin = new("https://example.com/");

1733string workingDirectory = ".";

1734 

1735string domain = origin.Authority;

1736List<Dictionary<string, string>> rows = [];

1737string[] files = Directory.GetFiles(Path.Combine(workingDirectory, "text", OutputDirectoryName(origin)), "*.txt");

1738Array.Sort(files, StringComparer.Ordinal);

1739foreach (string file in files)

1740{

1741 string title = TitleFromFilename(Path.GetFileName(file), domain);

1742 string text = RemoveNewlines(await File.ReadAllTextAsync(file));

1743 rows.Add(new() { ["fname"] = title, ["text"] = title + ". " + text });

1744}

1745 

1746Directory.CreateDirectory(Path.Combine(workingDirectory, "processed"));

1747using (StreamWriter output = new(Path.Combine(workingDirectory, "processed", "scraped.csv"), false, new UTF8Encoding(false)))

1748{

1749 await output.WriteLineAsync("id,fname,text");

1750 for (int index = 0; index < rows.Count; index++)

1751 {

1752 await output.WriteLineAsync(string.Join(",", index.ToString(CultureInfo.InvariantCulture),

1753 QuoteCsv(rows[index]["fname"]), QuoteCsv(rows[index]["text"])));

1754 }

1755}

1756 

1757static string OutputDirectoryName(Uri origin)

1758{

1759 string host = origin.IdnHost;

1760 bool ordinaryHost = origin.IsDefaultPort && host.Length <= 200

1761 && host.All(character => char.IsAsciiLetterOrDigit(character) || character is '.' or '-')

1762 && !host.EndsWith('.')

1763 && !Regex.IsMatch(host, @"^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)",

1764 RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);

1765 // Match the crawler's portable folder, preserving text/example.com for ordinary DNS.

1766 return ordinaryHost ? host : "site-" + Convert.ToHexString(

1767 SHA256.HashData(Encoding.UTF8.GetBytes(origin.Authority))).ToLowerInvariant();

1768}

1769 

1770static string TitleFromFilename(string filename, string domain)

1771{

1772 // PageFilename replaces these authority characters before writing the file.

1773 domain = Regex.Replace(domain, @"[\x00-\x1f/\\:*?""<>|]", "_");

1774 string title = Regex.Replace(Path.GetFileNameWithoutExtension(filename), "#[0-9a-f]{64}$", "");

1775 // Remove only the crawler's Windows-device escape for this authority.

1776 if (Regex.IsMatch(domain, @"^(con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³])(?:\.|$)",

1777 RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)

1778 && title.StartsWith("_" + domain, StringComparison.Ordinal))

1779 {

1780 title = title[1..];

1781 }

1782 if (title.StartsWith(domain + "_", StringComparison.Ordinal))

1783 {

1784 title = title[(domain.Length + 1)..];

1785 }

1786 else if (title == domain)

1787 {

1788 title = "index";

1789 }

1790 if (title.Length == 0)

1791 {

1792 title = "index";

1793 }

1794 return title.Replace("-", " ", StringComparison.Ordinal)

1795 .Replace("_", " ", StringComparison.Ordinal)

1796 .Replace("#update", "", StringComparison.Ordinal);

1797}

1798 

1799static string QuoteCsv(string value) => "\"" + value.Replace("\"", "\"\"", StringComparison.Ordinal) + "\"";

1800 

1801static string RemoveNewlines(string text)

1802{

1803 ArgumentNullException.ThrowIfNull(text);

1804 return Regex.Replace(

1805 text.Replace("\r\n", " ", StringComparison.Ordinal)

1806 .Replace("\r", " ", StringComparison.Ordinal)

1807 .Replace("\n", " ", StringComparison.Ordinal)

1808 .Replace(@"\n", " ", StringComparison.Ordinal),

1809 " {2,}", " ");

1810}

1811```

1812 

1379```ruby1813```ruby

1380require "csv"1814require "csv"

1381require "fileutils"1815require "fileutils"


1625}2059}

1626```2060```

1627 2061 

2062```csharp

2063using System.Text.Json;

2064using Microsoft.ML.Tokenizers;

2065using Microsoft.VisualBasic.FileIO;

2066 

2067var (counts, total) = SaveTokenHistogram();

2068 

2069static (int[] Counts, int Total) SaveTokenHistogram()

2070{

2071 List<string> texts = ReadColumn("processed/scraped.csv", "text");

2072 int[] counts = texts.Select(CountTokens).ToArray();

2073 int total = SaveHistogram(counts);

2074 return (counts, total);

2075}

2076 

2077 

2078static int CountTokens(string text) => TokenCounter.Encoding.CountTokens(text);

2079 

2080static int SaveHistogram(IReadOnlyList<int> counts)

2081{

2082 // Exact integer token counts form the bins; every row contributes once.

2083 var bins = counts.GroupBy(count => count).OrderBy(group => group.Key).ToArray();

2084 ScottPlot.Bar[] bars = bins.Select(group => new ScottPlot.Bar

2085 {

2086 Position = group.Key,

2087 Value = group.Count()

2088 }).ToArray();

2089 ScottPlot.Plot plot = new();

2090 if (bins.Length > 0)

2091 {

2092 plot.Add.Bars(bars);

2093 }

2094 plot.Title("Token count distribution");

2095 plot.XLabel("Tokens per text");

2096 plot.YLabel("Number of texts");

2097 plot.Axes.Bottom.Min = -1;

2098 plot.Axes.Left.Min = 0;

2099 plot.SavePng("token-histogram.png", 640, 400);

2100 return bins.Sum(group => group.Count());

2101}

2102 

2103// TextFieldParser handles quoted commas, escaped quotes, and multiline fields.

2104// Empty physical lines are ignored; quoted empty fields remain values.

2105static List<string> ReadColumn(string path, string column)

2106{

2107 using TextFieldParser parser = new(path, System.Text.Encoding.UTF8, true)

2108 {

2109 TextFieldType = FieldType.Delimited,

2110 HasFieldsEnclosedInQuotes = true,

2111 TrimWhiteSpace = false

2112 };

2113 parser.SetDelimiters(",");

2114 string[] header = parser.ReadFields() ?? throw new InvalidDataException("Missing CSV header.");

2115 if (header.Distinct(StringComparer.Ordinal).Count() != header.Length)

2116 {

2117 throw new InvalidDataException("Duplicate CSV column.");

2118 }

2119 int columnIndex = Array.IndexOf(header, column);

2120 if (columnIndex < 0)

2121 {

2122 throw new InvalidDataException($"Missing CSV column: {column}.");

2123 }

2124 List<string> values = [];

2125 while (!parser.EndOfData)

2126 {

2127 string[] fields = parser.ReadFields() ?? throw new InvalidDataException("Missing CSV record.");

2128 if (fields.Length != header.Length)

2129 {

2130 throw new InvalidDataException("CSV record length differs from its header.");

2131 }

2132 values.Add(fields[columnIndex]);

2133 }

2134 return values;

2135}

2136// The data package supplies this cached vocabulary without a network request.

2137static class TokenCounter

2138{

2139 internal static readonly TiktokenTokenizer Encoding = TiktokenTokenizer.CreateForEncoding("cl100k_base");

2140}

2141```

2142 

1628```ruby2143```ruby

1629require "csv"2144require "csv"

1630require "tiktoken_ruby"2145require "tiktoken_ruby"


1926}2441}

1927```2442```

1928 2443 

2444```csharp

2445using System.Globalization;

2446using System.Text;

2447using System.Text.Json;

2448using Microsoft.ML.Tokenizers;

2449using Microsoft.VisualBasic.FileIO;

2450 

2451List<string> texts = ReadColumn("processed/scraped.csv", "text");

2452List<string> chunks = texts.SelectMany(text => SplitIntoMany(text, 500)).ToList();

2453Directory.CreateDirectory("processed");

2454using (StreamWriter output = new("processed/chunks.csv", false, new UTF8Encoding(false)))

2455{

2456 await output.WriteLineAsync("text,n_tokens");

2457 foreach (string chunk in chunks)

2458 {

2459 string quoted = "\"" + chunk.Replace("\"", "\"\"", StringComparison.Ordinal) + "\"";

2460 await output.WriteLineAsync(quoted + "," + CountTokens(chunk).ToString(CultureInfo.InvariantCulture));

2461 }

2462}

2463// The embedding producer can consume the same chunks without CSV parsing.

2464await File.WriteAllTextAsync("processed/chunks.json", JsonSerializer.Serialize(chunks));

2465 

2466static int CountTokens(string text) => TokenCounter.Encoding.CountTokens(text);

2467 

2468static List<string> SplitIntoMany(string text, int maxTokens)

2469{

2470 ArgumentNullException.ThrowIfNull(text);

2471 ArgumentOutOfRangeException.ThrowIfLessThan(maxTokens, 1);

2472 List<string> chunks = [];

2473 if (string.IsNullOrWhiteSpace(text))

2474 {

2475 return chunks;

2476 }

2477 string chunk = "";

2478 string[] sentences = text.Split(". ", StringSplitOptions.None);

2479 for (int index = 0; index < sentences.Length; index++)

2480 {

2481 string sentence = sentences[index] + (index < sentences.Length - 1 ? "." : "");

2482 if (CountTokens(sentence) > maxTokens)

2483 {

2484 throw new ArgumentException("Split the overlong sentence before chunking.", nameof(text));

2485 }

2486 string candidate = chunk.Length == 0 ? sentence : chunk + " " + sentence;

2487 // Recount the complete candidate, including separators, at every step.

2488 if (CountTokens(candidate) > maxTokens)

2489 {

2490 chunks.Add(chunk);

2491 chunk = sentence;

2492 }

2493 else

2494 {

2495 chunk = candidate;

2496 }

2497 }

2498 if (chunk.Length > 0)

2499 {

2500 chunks.Add(chunk);

2501 }

2502 return chunks;

2503}

2504 

2505// TextFieldParser handles quoted commas, escaped quotes, and multiline fields.

2506// Empty physical lines are ignored; quoted empty fields remain values.

2507static List<string> ReadColumn(string path, string column)

2508{

2509 using TextFieldParser parser = new(path, System.Text.Encoding.UTF8, true)

2510 {

2511 TextFieldType = FieldType.Delimited,

2512 HasFieldsEnclosedInQuotes = true,

2513 TrimWhiteSpace = false

2514 };

2515 parser.SetDelimiters(",");

2516 string[] header = parser.ReadFields() ?? throw new InvalidDataException("Missing CSV header.");

2517 if (header.Distinct(StringComparer.Ordinal).Count() != header.Length)

2518 {

2519 throw new InvalidDataException("Duplicate CSV column.");

2520 }

2521 int columnIndex = Array.IndexOf(header, column);

2522 if (columnIndex < 0)

2523 {

2524 throw new InvalidDataException($"Missing CSV column: {column}.");

2525 }

2526 List<string> values = [];

2527 while (!parser.EndOfData)

2528 {

2529 string[] fields = parser.ReadFields() ?? throw new InvalidDataException("Missing CSV record.");

2530 if (fields.Length != header.Length)

2531 {

2532 throw new InvalidDataException("CSV record length differs from its header.");

2533 }

2534 values.Add(fields[columnIndex]);

2535 }

2536 return values;

2537}

2538 

2539// The data package supplies this cached vocabulary without a network request.

2540static class TokenCounter

2541{

2542 internal static readonly TiktokenTokenizer Encoding = TiktokenTokenizer.CreateForEncoding("cl100k_base");

2543}

2544```

2545 

1929```ruby2546```ruby

1930require "csv"2547require "csv"

1931require "json"2548require "json"


2131}2748}

2132```2749```

2133 2750 

2751```csharp

2752using System.Text.Json;

2753using Microsoft.ML.Tokenizers;

2754using Microsoft.VisualBasic.FileIO;

2755 

2756var (counts, total) = SaveTokenHistogram();

2757 

2758static (int[] Counts, int Total) SaveTokenHistogram()

2759{

2760 List<string> texts = ReadColumn("processed/chunks.csv", "text");

2761 int[] counts = texts.Select(CountTokens).ToArray();

2762 int total = SaveHistogram(counts);

2763 return (counts, total);

2764}

2765 

2766 

2767static int CountTokens(string text) => TokenCounter.Encoding.CountTokens(text);

2768 

2769static int SaveHistogram(IReadOnlyList<int> counts)

2770{

2771 // Exact integer token counts form the bins; every row contributes once.

2772 var bins = counts.GroupBy(count => count).OrderBy(group => group.Key).ToArray();

2773 ScottPlot.Bar[] bars = bins.Select(group => new ScottPlot.Bar

2774 {

2775 Position = group.Key,

2776 Value = group.Count()

2777 }).ToArray();

2778 ScottPlot.Plot plot = new();

2779 if (bins.Length > 0)

2780 {

2781 plot.Add.Bars(bars);

2782 }

2783 plot.Title("Token count distribution");

2784 plot.XLabel("Tokens per text");

2785 plot.YLabel("Number of texts");

2786 plot.Axes.Bottom.Min = -1;

2787 plot.Axes.Left.Min = 0;

2788 plot.SavePng("token-histogram.png", 640, 400);

2789 return bins.Sum(group => group.Count());

2790}

2791 

2792// TextFieldParser handles quoted commas, escaped quotes, and multiline fields.

2793// Empty physical lines are ignored; quoted empty fields remain values.

2794static List<string> ReadColumn(string path, string column)

2795{

2796 using TextFieldParser parser = new(path, System.Text.Encoding.UTF8, true)

2797 {

2798 TextFieldType = FieldType.Delimited,

2799 HasFieldsEnclosedInQuotes = true,

2800 TrimWhiteSpace = false

2801 };

2802 parser.SetDelimiters(",");

2803 string[] header = parser.ReadFields() ?? throw new InvalidDataException("Missing CSV header.");

2804 if (header.Distinct(StringComparer.Ordinal).Count() != header.Length)

2805 {

2806 throw new InvalidDataException("Duplicate CSV column.");

2807 }

2808 int columnIndex = Array.IndexOf(header, column);

2809 if (columnIndex < 0)

2810 {

2811 throw new InvalidDataException($"Missing CSV column: {column}.");

2812 }

2813 List<string> values = [];

2814 while (!parser.EndOfData)

2815 {

2816 string[] fields = parser.ReadFields() ?? throw new InvalidDataException("Missing CSV record.");

2817 if (fields.Length != header.Length)

2818 {

2819 throw new InvalidDataException("CSV record length differs from its header.");

2820 }

2821 values.Add(fields[columnIndex]);

2822 }

2823 return values;

2824}

2825// The data package supplies this cached vocabulary without a network request.

2826static class TokenCounter

2827{

2828 internal static readonly TiktokenTokenizer Encoding = TiktokenTokenizer.CreateForEncoding("cl100k_base");

2829}

2830```

2831 

2134```ruby2832```ruby

2135require "json"2833require "json"

2136require "tiktoken_ruby"2834require "tiktoken_ruby"


2546System.out.println(vectors.get(0));3244System.out.println(vectors.get(0));

2547```3245```

2548 3246 

3247```csharp

3248using System.Text;

3249using System.Text.Json;

3250using Microsoft.VisualBasic.FileIO;

3251 

3252namespace OpenAI.Docs.Examples.TutorialCrawlWebsiteEmbeddings.LoadEmbeddings;

3253 

3254internal static class LoadEmbeddingsSample

3255{

3256 

3257internal static double[] LoadEmbeddings()

3258 {

3259 // Run the embedding producer first; this program never invents missing input.

3260 List<double[]> vectors = ReadColumn("processed/embeddings.csv", "embeddings")

3261 .Select(ParseVector).ToList();

3262 if (vectors.Count == 0)

3263 {

3264 throw new InvalidDataException("The CSV must contain at least one embedding.");

3265 }

3266 int dimensions = vectors[0].Length;

3267 if (vectors.Any(vector => vector.Length != dimensions))

3268 {

3269 throw new InvalidDataException("All embeddings must have the same dimensions.");

3270 }

3271 double[] first = vectors[0];

3272 Console.WriteLine(JsonSerializer.Serialize(first));

3273 return first;

3274 }

3275 internal static double[] ParseVector(string json)

3276 {

3277 using JsonDocument document = JsonDocument.Parse(json);

3278 if (document.RootElement.ValueKind != JsonValueKind.Array)

3279 {

3280 throw new InvalidDataException("An embedding must be a JSON array.");

3281 }

3282 List<double> values = [];

3283 foreach (JsonElement item in document.RootElement.EnumerateArray())

3284 {

3285 if (item.ValueKind != JsonValueKind.Number || !item.TryGetDouble(out double value)

3286 || !double.IsFinite(value))

3287 {

3288 throw new InvalidDataException("Embedding values must be finite JSON numbers.");

3289 }

3290 values.Add(value);

3291 }

3292 if (values.Count == 0)

3293 {

3294 throw new InvalidDataException("An embedding must not be empty.");

3295 }

3296 return values.ToArray();

3297 }

3298 

3299 // TextFieldParser handles quoted commas, escaped quotes, and multiline fields.

3300 // Empty physical lines are ignored; quoted empty fields remain values.

3301 private static List<string> ReadColumn(string path, string column)

3302 {

3303 using TextFieldParser parser = new(path, Encoding.UTF8, true)

3304 {

3305 TextFieldType = FieldType.Delimited,

3306 HasFieldsEnclosedInQuotes = true,

3307 TrimWhiteSpace = false

3308 };

3309 parser.SetDelimiters(",");

3310 string[] header = parser.ReadFields() ?? throw new InvalidDataException("Missing CSV header.");

3311 if (header.Distinct(StringComparer.Ordinal).Count() != header.Length)

3312 {

3313 throw new InvalidDataException("Duplicate CSV column.");

3314 }

3315 int columnIndex = Array.IndexOf(header, column);

3316 if (columnIndex < 0)

3317 {

3318 throw new InvalidDataException($"Missing CSV column: {column}.");

3319 }

3320 List<string> values = [];

3321 while (!parser.EndOfData)

3322 {

3323 string[] fields = parser.ReadFields() ?? throw new InvalidDataException("Missing CSV record.");

3324 if (fields.Length != header.Length)

3325 {

3326 throw new InvalidDataException("CSV record length differs from its header.");

3327 }

3328 values.Add(fields[columnIndex]);

3329 }

3330 return values;

3331 }

3332}

3333```

3334 

2549```ruby3335```ruby

2550require "csv"3336require "csv"

2551require "json"3337require "json"