Wrong url, can someone explai why and the correct one?

i actually remade the code and everything seems right and i made so i can see the errors and the url is invalid
heres the error:
image

heres the code:

public static async Task GetGeminiResponse(string prompt)
{
string endpoint = “https://generativelanguage.googleapis.com/v1beta/”;
string apiKey = “my key here”;
using (HttpClient client = new HttpClient())
{
string url = $“{endpoint}?key={apiKey}”;
var requestBody = new
{
query = prompt,
options = new { max_tokens = 100 }
};
var content = new StringContent(JsonConvert.SerializeObject(requestBody), Encoding.UTF8, “application/json”);
try
{
var response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
var responseString = await response.Content.ReadAsStringAsync();
Console.WriteLine(“Response from API: " + responseString);
dynamic responseJson = JsonConvert.DeserializeObject(responseString);
if (responseJson != null && responseJson.choices != null && responseJson.choices.Count > 0)
{
return responseJson.choices[0].text.ToString();
}
else
{
Console.WriteLine(“Invalid response structure or empty response.”);
return “API response is invalid or empty.”;
}
}
else
{
Console.WriteLine($“HTTP request failed with status code: {response.StatusCode}”);
return $“HTTP request failed with status code: {response.StatusCode}”;
}
}
catch (Exception ex)
{
Console.WriteLine($“Error occurred: {ex.Message}”);
return $“Error occurred: {ex.Message}”;
}
}
}
private async void Ask_Click(object sender, RoutedEventArgs e)
{
string userQuestion = What.Text;
if (!string.IsNullOrEmpty(userQuestion))
{
string predefinedPrompt = “Be nice while answering.”;
string combinedPrompt = $”{predefinedPrompt}\n\nUser: {userQuestion}";
string response = await GetGeminiResponse(combinedPrompt);
Response1.Text = response;
}
else
{
MessageBox.Show(“Please enter a question.”);
}
}

Hello

Your url is wrong, here the structure of url
https://generativelanguage.googleapis.com/v1beta/models/MODEL:generateContent?key=YOURKEY

Select the model you want can be “gemini-1.5-pro” for example

Stéphane

2 Likes

In addition to what @Stephane_G said, the format for requestBody needs to match the format defined by the request body in the API. You can also see what this JSON format looks like if you use AI Studio and click “Show Code” and then select the “cURL” option.

(As an aside - it would help a lot if you keep replying rather than creating new threads on the same topic. It took me a bit to realize what you meant by “I actually remade the code”.)

1 Like