clawdforge/clients/csharp/examples/Basic/Program.cs

80 lines
2.4 KiB
C#

using System.Text.Json;
using Clawdforge;
using Clawdforge.Exceptions;
using Clawdforge.Models;
// Quickstart for the clawdforge C# SDK.
//
// Set environment vars:
// CLAWDFORGE_URL=http://192.168.0.5:8800
// CLAWDFORGE_TOKEN=cf_<your-app-token>
var baseUrl = Environment.GetEnvironmentVariable("CLAWDFORGE_URL")
?? "http://localhost:8800";
var token = Environment.GetEnvironmentVariable("CLAWDFORGE_TOKEN")
?? throw new InvalidOperationException("CLAWDFORGE_TOKEN env var is required");
using var client = new ForgeClient(new ForgeOptions
{
BaseUrl = baseUrl,
Token = token,
});
// 60s ceiling for the whole demo via cancellation.
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(120));
var ct = cts.Token;
try
{
var h = await client.HealthzAsync(ct);
Console.WriteLine($"clawdforge ok={h.Ok} claude_present={h.ClaudePresent} version={h.ClaudeVersion}");
var res = await client.RunAsync(new RunRequest
{
Prompt = "Reply with JSON: {\"hello\": \"world\"}",
Model = "sonnet",
TimeoutSecs = 60,
}, ct);
Console.WriteLine($"duration: {res.DurationMs}ms stop_reason: {res.StopReason}");
// res.Result is a JsonElement — caller narrows by ValueKind.
if (res.Result.ValueKind == JsonValueKind.Object
&& res.Result.TryGetProperty("hello", out var hello))
{
Console.WriteLine($"hello: {hello.GetString()}");
}
else
{
Console.WriteLine($"raw result: {res.AsText()}");
}
// Optional file-upload demo: only runs if a path is in argv[0].
if (args.Length > 0 && File.Exists(args[0]))
{
var ft = await client.UploadFileAsync(args[0], ttlSecs: 3600, ct);
Console.WriteLine($"uploaded: token={ft.Token} size={ft.Size}");
var withFile = await client.RunAsync(new RunRequest
{
Prompt = "Describe the attached file.",
Files = new[] { ft.Token },
}, ct);
Console.WriteLine($"file run: {withFile.AsText()}");
}
}
catch (ForgeAuthException ex)
{
Console.Error.WriteLine($"auth failed: {ex.StatusCode}: {ex.Body}");
Environment.Exit(2);
}
catch (ForgeApiException ex)
{
Console.Error.WriteLine($"api error {ex.StatusCode}: {ex.Body}");
Environment.Exit(3);
}
catch (ForgeTransportException ex)
{
Console.Error.WriteLine($"transport: {ex.Message}");
Environment.Exit(4);
}