Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Cohere
https://tryagi.github.io/Cohere
Admin
A fully-generated C# SDK for the Cohere API with support for chat, embeddings, and
...
Tokens:
4,506
Snippets:
54
Trust Score:
9.7
Update:
4 months ago
Context
Chat
Benchmark
0
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Install Cohere Package Source: https://tryagi.github.io/Cohere/guides/meai Install the Cohere NuGet package using the dotnet CLI. ```bash dotnet add package Cohere ``` -------------------------------- ### Multi-Turn Chat with Tool Calling Source: https://tryagi.github.io/Cohere Implements a multi-turn chat conversation where the model can call tools. This example defines a 'GetWeather' tool and handles function calls and results. ```csharp using var client = GetAuthenticatedCohereClient(); Meai.IChatClient chatClient = client; var getWeatherTool = AIFunctionFactory.Create( (string location) => $ ``` ```csharp "The weather in {location} is sunny, 72°F", "GetWeather", "Gets the current weather for a location"); var messages = new List<Meai.ChatMessage> { new(Meai.ChatRole.User, "What's the weather in Seattle?"), }; var options = new Meai.ChatOptions { ModelId = "command-r-plus", Tools = [getWeatherTool], }; // First turn: model should call the tool var response = await chatClient.GetResponseAsync(messages, options); var functionCall = response.Messages .SelectMany(m => m.Contents) .OfType<FunctionCallContent>() .FirstOrDefault(); // Add assistant response with tool call and tool result messages.AddRange(response.Messages); var toolResult = await getWeatherTool.InvokeAsync( functionCall!.Arguments is { } args ? new AIFunctionArguments(args) : null); messages.Add(new Meai.ChatMessage(Meai.ChatRole.Tool, [ new FunctionResultContent(functionCall.CallId, toolResult), ])); // Second turn: model should respond with the weather info var finalResponse = await chatClient.GetResponseAsync(messages, options); ``` -------------------------------- ### Get Unknown Service Metadata Source: https://tryagi.github.io/Cohere Demonstrates retrieving service metadata for an unknown key, which should return null. Uses ChatClientExtensions.GetService with a specified serviceKey. ```csharp using var client = CreateTestClient(); Meai.IChatClient chatClient = client; var result = Meai.ChatClientExtensions.GetService<Meai.ChatClientMetadata>(chatClient, serviceKey: "unknown"); ``` -------------------------------- ### Get Embedding Generator Service with Unknown Key Source: https://tryagi.github.io/Cohere/examples/embedding-generator-get-service-returns-null-for-unknown-key Use this snippet to test the behavior of `GetService` when an unknown service key is provided. It expects `null` as the result. ```csharp using var client = CreateTestClient(); Meai.IEmbeddingGenerator<string, Meai.Embedding<float>> generator = client; var result = Meai.EmbeddingGeneratorExtensions.GetService<Meai.EmbeddingGeneratorMetadata>(generator, serviceKey: "unknown"); ``` -------------------------------- ### Chat with Cohere Source: https://tryagi.github.io/Cohere/examples/generate Initiates a chat conversation with the Cohere API to get a response. Requires the Cohere API key and the Cohere client library. ```csharp using var client = new CohereClient(apiKey); var response = await client.ChatAsync(new ChatRequest { Message = "Hello, Cohere! Can you tell me a joke?", }); Console.WriteLine("Cohere Response:"); Console.WriteLine(response.Text); ``` -------------------------------- ### Get Chat Service Metadata for Unknown Key Source: https://tryagi.github.io/Cohere/examples/chat-client-get-service-returns-null-for-unknown-key Retrieves chat client metadata for a non-existent service key. This method returns null when the key is not found. Ensure `using Cohere;` is in scope and `CreateTestClient()` is available. ```csharp using var client = CreateTestClient(); Meai.IChatClient chatClient = client; var result = Meai.ChatClientExtensions.GetService<Meai.ChatClientMetadata>(chatClient, serviceKey: "unknown"); ``` -------------------------------- ### Get Chat Response Source: https://tryagi.github.io/Cohere Retrieves a non-streaming chat response from the Cohere model. Specify the model ID in ChatOptions. ```csharp using var client = GetAuthenticatedCohereClient(); Meai.IChatClient chatClient = client; var response = await chatClient.GetResponseAsync( [ new Meai.ChatMessage(Meai.ChatRole.User, "Generate 5 random words.") ], new Meai.ChatOptions { ModelId = "command-r-plus", }); ``` -------------------------------- ### Get Underlying Service from Embedding Generator Source: https://tryagi.github.io/Cohere/examples/embedding-generator-get-service-returns-self Use this to access the original client when you need to call methods not exposed by the `IEmbeddingGenerator` interface. Ensure `Cohere` is in scope. ```csharp using var client = CreateTestClient(); Meai.IEmbeddingGenerator<string, Meai.Embedding<float>> generator = client; var self = Meai.EmbeddingGeneratorExtensions.GetService<CohereClient>(generator); ``` -------------------------------- ### Embedding Generator Single Text Source: https://tryagi.github.io/Cohere Provides an example of generating an embedding for a single piece of text. This is suitable for scenarios where only one text needs embedding. ```csharp using var client = GetAuthenticatedCohereClient(); Meai.IEmbeddingGenerator<string, Meai.Embedding<float>> generator = client; var embeddings = await generator.GenerateAsync( ["Hello, world!"], new Meai.EmbeddingGenerationOptions { ModelId = "embed-english-v3.0", }); ``` -------------------------------- ### Retrieve Embedding Generator Metadata Source: https://tryagi.github.io/Cohere/examples/embedding-generator-get-service-returns-metadata This snippet shows how to get the EmbeddingGeneratorMetadata from an IEmbeddingGenerator instance. Ensure you have the Cohere SDK imported and your API key configured. ```csharp using var client = CreateTestClient(); Meai.IEmbeddingGenerator<string, Meai.Embedding<float>> generator = client; var metadata = Meai.EmbeddingGeneratorExtensions.GetService<Meai.EmbeddingGeneratorMetadata>(generator); ``` -------------------------------- ### Basic IChatClient Usage with Namespace Alias Source: https://tryagi.github.io/Cohere/guides/meai Demonstrates basic usage of the IChatClient interface from Microsoft.Extensions.AI, requiring a namespace alias for the Cohere SDK's generated interface. ```csharp using Cohere; using Meai = Microsoft.Extensions.AI; using var client = new CohereClient(apiKey); Meai.IChatClient chatClient = client; var response = await chatClient.GetResponseAsync( "What is the capital of France?", new Meai.ChatOptions { ModelId = "command-r-08-2024", }); Console.WriteLine(response.Text); ``` -------------------------------- ### Basic IEmbeddingGenerator Usage Source: https://tryagi.github.io/Cohere/guides/meai Demonstrates the basic usage of the IEmbeddingGenerator interface from Microsoft.Extensions.AI with the Cohere SDK to generate embeddings for a list of strings. ```csharp using Cohere; using Meai = Microsoft.Extensions.AI; using var client = new CohereClient(apiKey); Meai.IEmbeddingGenerator<string, Meai.Embedding<float>> generator = client; var embeddings = await generator.GenerateAsync( ["Hello, world!", "How are you?"], new Meai.EmbeddingGenerationOptions { ModelId = "embed-english-v3.0", }); foreach (var embedding in embeddings) { Console.WriteLine($"Dimensions: {embedding.Vector.Length}"); } ``` -------------------------------- ### Multi-Turn Chat with Tool Calling Source: https://tryagi.github.io/Cohere/examples/chat-client-tool-calling-multi-turn This C# snippet demonstrates a full multi-turn chat interaction using the Cohere SDK. It includes defining a tool, making an initial request, processing the tool call, invoking the tool, and sending the result back for a final answer. Ensure you have authenticated the client and the necessary using statements are in scope. ```csharp using var client = GetAuthenticatedCohereClient(); Meai.IChatClient chatClient = client; var getWeatherTool = AIFunctionFactory.Create( (string location) => $"The weather in {location} is sunny, 72°F", "GetWeather", "Gets the current weather for a location"); var messages = new List<Meai.ChatMessage> { new(Meai.ChatRole.User, "What's the weather in Seattle?"), }; var options = new Meai.ChatOptions { ModelId = "command-r-plus", Tools = [getWeatherTool], }; // First turn: model should call the tool var response = await chatClient.GetResponseAsync(messages, options); var functionCall = response.Messages .SelectMany(m => m.Contents) .OfType<FunctionCallContent>() .FirstOrDefault(); // Add assistant response with tool call and tool result messages.AddRange(response.Messages); var toolResult = await getWeatherTool.InvokeAsync( functionCall!.Arguments is { } args ? new AIFunctionArguments(args) : null); messages.Add(new Meai.ChatMessage(Meai.ChatRole.Tool, [ new FunctionResultContent(functionCall.CallId, toolResult), ])); // Second turn: model should respond with the weather info var finalResponse = await chatClient.GetResponseAsync(messages, options); ``` -------------------------------- ### Accessing IChatClient Metadata Source: https://tryagi.github.io/Cohere/guides/meai Illustrates how to access service metadata and the underlying client instance using extension methods when using the Meai alias for IChatClient. ```csharp var metadata = Meai.ChatClientExtensions.GetService<Meai.ChatClientMetadata>(chatClient); var self = Meai.ChatClientExtensions.GetService<CohereClient>(chatClient); ``` -------------------------------- ### IChatClient Tool Calling with CSharpToJsonSchema Source: https://tryagi.github.io/Cohere/guides/meai Shows how to use IChatClient for tool calling by defining tools with CSharpToJsonSchema and passing them to the chat options. ```csharp using CSharpToJsonSchema; using Meai = Microsoft.Extensions.AI; [GenerateJsonSchema] public interface IWeatherTools { [Description("Gets the current weather for a location.")] string GetWeather( [Description("The city name")] string city); } Meai.IChatClient chatClient = client; var service = new WeatherToolsService(); var response = await chatClient.GetResponseAsync( "What's the weather in Paris?", new Meai.ChatOptions { ModelId = "command-r-08-2024", Tools = service.AsTools().AsAITools(), }); ``` -------------------------------- ### Generate Text with Cohere Source: https://tryagi.github.io/Cohere Basic usage of the Cohere SDK to generate text based on a prompt. Requires an API key for authentication. ```csharp using Cohere; using var client = new CohereClient(apiKey); var response = await client.GenerateAsync(new GenerateRequest { Prompt = "Hello, Cohere! Can you tell me a joke?", }); Console.WriteLine("Cohere Response:"); Console.WriteLine(response.Generations[0].Text); ``` -------------------------------- ### Retrieve CohereClient from Chat Client Source: https://tryagi.github.io/Cohere/examples/chat-client-get-service-returns-self Use GetService to cast a generic chat client to its specific implementation. Ensure the Cohere namespace is imported and your API key is configured. ```csharp using var client = CreateTestClient(); Meai.IChatClient chatClient = client; var self = Meai.ChatClientExtensions.GetService<CohereClient>(chatClient); ``` -------------------------------- ### Microsoft.Extensions.AI Integration Source: https://tryagi.github.io/Cohere Integrates the Cohere SDK with Microsoft.Extensions.AI interfaces for chat and embedding. Use the 'Meai' alias to avoid naming conflicts. ```csharp using Cohere; using Meai = Microsoft.Extensions.AI; // IChatClient Meai.IChatClient chatClient = new CohereClient(apiKey); var response = await chatClient.GetResponseAsync( [new Meai.ChatMessage(Meai.ChatRole.User, "Hello!")], new Meai.ChatOptions { ModelId = "command-r-08-2024" }); // IEmbeddingGenerator Meai.IEmbeddingGenerator<string, Meai.Embedding<float>> generator = new CohereClient(apiKey); var embeddings = await generator.GenerateAsync( ["Hello, world!"], new Meai.EmbeddingGenerationOptions { ModelId = "embed-english-v3.0" }); ``` -------------------------------- ### Chat Client - Generate Five Random Words Source: https://tryagi.github.io/Cohere/examples/chat-client-five-random-words This snippet shows how to authenticate with the Cohere client and send a request to generate five random words using the 'command-r-plus' model. Ensure 'using Cohere;' is in scope and 'apiKey' is set. ```csharp using var client = GetAuthenticatedCohereClient(); Meai.IChatClient chatClient = client; var response = await chatClient.GetResponseAsync( [ new Meai.ChatMessage(Meai.ChatRole.User, "Generate 5 random words.") ], new Meai.ChatOptions { ModelId = "command-r-plus", }); ``` -------------------------------- ### Single Turn Chat Client Tool Call Source: https://tryagi.github.io/Cohere/examples/chat-client-tool-calling-single-turn Use this snippet to make a single-turn chat request that involves tool calling. Ensure you have authenticated the Cohere client and defined your tools. ```csharp using var client = GetAuthenticatedCohereClient(); Meai.IChatClient chatClient = client; var getWeatherTool = AIFunctionFactory.Create( (string location) => $"The weather in {location} is sunny, 72°F", "GetWeather", "Gets the current weather for a location"); var response = await chatClient.GetResponseAsync( [new Meai.ChatMessage(Meai.ChatRole.User, "What's the weather in Seattle?")], new Meai.ChatOptions { ModelId = "command-r-plus", Tools = [getWeatherTool], }); var functionCall = response.Messages .SelectMany(m => m.Contents) .OfType<FunctionCallContent>() .FirstOrDefault(); ``` -------------------------------- ### Retrieve ChatClientMetadata Source: https://tryagi.github.io/Cohere/examples/chat-client-get-service-returns-chat-client-metadata Use the GetService extension method to cast the chat client to its metadata type. This requires the Cohere namespace to be in scope. ```csharp using var client = CreateTestClient(); Meai.IChatClient chatClient = client; var metadata = Meai.ChatClientExtensions.GetService<Meai.ChatClientMetadata>(chatClient); ``` -------------------------------- ### Chat Client Streaming Response Source: https://tryagi.github.io/Cohere/examples/chat-client-five-random-words-streaming This C# snippet demonstrates streaming a chat response from the Cohere API. It's useful for applications requiring real-time text generation, such as chatbots or interactive content creation. Ensure you have authenticated the client and specified the desired model. ```csharp using var client = GetAuthenticatedCohereClient(); Meai.IChatClient chatClient = client; var updates = chatClient.GetStreamingResponseAsync( [ new Meai.ChatMessage(Meai.ChatRole.User, "Generate 5 random words.") ], new Meai.ChatOptions { ModelId = "command-r-plus", }); var deltas = new List<string>(); await foreach (var update in updates) { if (!string.IsNullOrWhiteSpace(update.Text)) { deltas.Add(update.Text); } } ``` -------------------------------- ### Generate Embeddings for Single Text Source: https://tryagi.github.io/Cohere/examples/embedding-generator-single-text Use the `IEmbeddingGenerator` interface to generate embeddings for a list containing a single string. Ensure you have authenticated the Cohere client and specify the desired model ID. ```csharp using var client = GetAuthenticatedCohereClient(); Meai.IEmbeddingGenerator<string, Meai.Embedding<float>> generator = client; var embeddings = await generator.GenerateAsync( ["Hello, world!"], new Meai.EmbeddingGenerationOptions { ModelId = "embed-english-v3.0", }); ``` -------------------------------- ### Generate Embeddings for Batch Texts Source: https://tryagi.github.io/Cohere/examples/embedding-generator-batch-texts Use this snippet to generate embeddings for a list of strings. Ensure you have authenticated the Cohere client and specified the desired model ID. ```csharp using var client = GetAuthenticatedCohereClient(); Meai.IEmbeddingGenerator<string, Meai.Embedding<float>> generator = client; var embeddings = await generator.GenerateAsync( ["Hello", "World", "Test"], new Meai.EmbeddingGenerationOptions { ModelId = "embed-english-v3.0", }); foreach (var embedding in embeddings) { } ```