DEV Community

Xiaoyun Zhang
Xiaoyun Zhang

Posted on

Build a Weather Chatbot with DeepSeek v3 and OpenAI SDK: A Step-by-Step Guide

In this tutorial, we'll walk through creating a weather chatbot using DeepSeek v3 and OpenAI SDK for .NET. The complete source code can be found in this GitHub repository

Prerequisites

  • .NET SDK (8.0 or later)
  • DeepSeek API key (You can sign up for an account with ¥10 credit at DeepSeek

Create a New Console Project

First, let's set up our project by creating a new console application and installing required OpenAI SDK packages:

dotnet new console -n WeatherChatbot
cd WeatherChatbot
dotnet add package OpenAI
Enter fullscreen mode Exit fullscreen mode

Setting Up the DeepSeek Client

Instead of using the default OpenAI endpoints, we'll configure our client to use DeepSeek's API. The DeepSeek API is compatible with the OpenAI API, so we can use the OpenAI SDK to connect to it:

var option = new OpenAIClientOptions
{
    // Set the DeepSeek API endpoint
    Endpoint = new ("https://api.deepseek.com"),
};
var client = new OpenAIClient(new ApiKeyCredential(DEEP_SEEK_API_KEY), option);

// use deepseek-chat model which points to the latest v3 model
var chatClient = client.GetChatClient("deepseek-chat");
Enter fullscreen mode Exit fullscreen mode

Defining Function Tools

One of the key features we'll be using is the ability to define "tools" - functions that the language model can call when it needs specific information. We'll create one tool to retreive dummy weather information for a given location:

var getCurrentWeatherTool = ChatTool.CreateFunctionTool(
    functionName: nameof(GetCurrentWeather),
    functionDescription: "Get the current weather in a given location",
    functionParameters: BinaryData.FromBytes("""
        {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "The city and state, e.g. Boston, MA"
                },
                "unit": {
                    "type": "string",
                    "enum": [ "celsius", "fahrenheit" ],
                    "description": "The temperature unit to use. Infer this from the specified location."
                }
            },
            "required": [ "location" ]
        }
        """u8.ToArray())
);
Enter fullscreen mode Exit fullscreen mode

Implementing the Chat Loop

The heart of our chatbot is the conversation loop. Here's how we handle the interaction:

  1. Initialize the conversation with a user message
  2. Process the message using the DeepSeek model
  3. Handle any tool calls requested by the model
  4. Continue the conversation based on the model's response
var messages = new List<ChatMessage>()
{
    new UserChatMessage("What's the weather like in San Francisco?"),
};

bool requiresAction;

do
{
    requiresAction = false;
    var useToolCall = messages.Last() is not ToolChatMessage;
    var completion = useToolCall
        ? await chatClient.CompleteChatAsync(messages, new () { Tools = {getCurrentWeatherTool}})
        : await chatClient.CompleteChatAsync(messages);

    // Handle different completion scenarios
    switch (completion.Value.FinishReason)
    {
        case ChatFinishReason.Stop:
            {
                messages.Add(new AssistantChatMessage(completion));
                Console.WriteLine(completion.Value.Content[0].Text);
                break;
            }
        case ChatFinishReason.ToolCalls:
            {
                // Handle tool calls
                // ...
            }
        // Handle other cases
    }
} while (requiresAction);
Enter fullscreen mode Exit fullscreen mode

Implementing the Weather Functions

For this example, we've implemented simple placeholder functions for getting weather information:

static string GetCurrentWeather(string location, string unit = "celsius")
{
    // Call the weather API here
    return $"The weather in {location} is 72 degrees {unit}.";
}
Enter fullscreen mode Exit fullscreen mode

In a production environment, you'd want to replace these with actual API calls to weather and location services.

Run the Chatbot

Now that we've set up our chatbot, we can run it and see the output:

Image description

Top comments (0)