반응형

0. 3주차 과제 (저장소 링크)

3주차 과제는 Azure Function App + ChatGPT 결합을 해보는 것이다.

기존 3주차 실습에서는 azure.sdk를 써서 했는데, 우리는 이걸 사용하지 말고 chatgpt 실제로 api 호출을 해봐야한다.

 

1. Azure Functions Application 생성

2주차부터 시작했던 것과 마찬가지로 원하는 경로에 func init을 통해 애저 펑션을 만들어준다.

- 2주차 애저펑션 애플리케이션 만드는법 참고

https://dlwns7267.tistory.com/771

 

2. Program.cs 파일 소스 코드 변경

ConfigureFunctionsWorkerDefaults를 아래와 같이 변경한다.

⇒ ConfigureFunctionsWorkerDefaults(worker => worker.UseNewtonsoftJson())

 

3. launch.Settings.json 포트 변경

launch.Settings.json

json 파일에서 port 번호를 7071로 변경해준다.

 

4. local.settings.json 파일 설정

{
    "IsEncrypted": false,
    "Values": {
        "AzureWebJobsStorage": "UseDevelopmentStorage=true",
        "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",

        "AOAI_Endpoint": "https://api.openai.com/v1/chat/completions",
        "AOAI_ApiKey": "openaikey",
        "AOAI_DeploymentId": "gpt-3.5-turbo"
    }
}

- apikey 생성 주소

https://platform.openai.com/account/api-keys

해당 주소에서 apikey를 생성한다.

 

5. dotnet package 설정

dotnet add package 명령어를 이용하여 필요한 패키지를 업데이트 및 설치를 해준다.

  <ItemGroup>
    <PackageReference Include="Microsoft.Azure.Functions.Worker" Version="1.18.0" />
    <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http" Version="3.0.13" />
    <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.OpenApi" Version="1.5.1" />
    <PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="1.13.0" />
  </ItemGroup>

 

6. payload 가져오기

- 주석 확인할 것.

using System.Net;
using System.Text;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Attributes;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace assignment3
{
    public class ChatGPT
    {
        private readonly ILogger _logger;

        public ChatGPT(ILoggerFactory loggerFactory)
        {
            _logger = loggerFactory.CreateLogger<ChatGPT>();
        }

        [Function("ChatGPT")]

        [OpenApiOperation(operationId: nameof(ChatGPT.Run), tags: new[] { "name" })]
        [OpenApiRequestBody(contentType: "text/plain", bodyType: typeof(string), Required = true, Description = "The request body")]
        [OpenApiResponseWithBody(statusCode: HttpStatusCode.OK, contentType: "text/plain", bodyType: typeof(string), Description = "The OK response")]

        public async Task<HttpResponseData> Run([HttpTrigger(AuthorizationLevel.Function, "POST", Route = "completions")] HttpRequestData req)
        {
            _logger.LogInformation("C# HTTP trigger function processed a request.");

            // 요청 payload 읽어들인 것
            var prompt = req.ReadAsString(); 

            // 인스턴스 생성
            var endpoint = Environment.GetEnvironmentVariable("AOAI_Endpoint");
            var credential = Environment.GetEnvironmentVariable("AOAI_ApiKey");
            var deploymentId = Environment.GetEnvironmentVariable("AOAI_DeploymentId");

            using (var httpClient = new HttpClient())
            {
                // httpClient 생성 및 apikey 추가
                httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {credential}");
                httpClient.DefaultRequestHeaders.Add("User-Agent", "Azure Function");

                // API 요청 데이터 생성
                var reqbody = new
                {
                    model = deploymentId,
                    messages = new[]
                    {
                        new {role = "system", content =  "You are a helpful assistant. You are very good at summarizing the given text into 2-3 bullet points."},
                        new {role = "user", content = prompt}
                    },
                    
                    max_tokens = 800,
                    temperature = 0.7f,
                };

                var content = new StringContent(JsonConvert.SerializeObject(reqbody), Encoding.UTF8, "application/json");

                // API 호출
                var responseGPT = httpClient.PostAsync(endpoint, content).Result;
                string message = responseGPT.Content.ReadAsStringAsync().Result;

                var response = req.CreateResponse(HttpStatusCode.OK);
                response.Headers.Add("Content-Type", "text/plain; charset=utf-8");

                response.WriteString(message);

                return response;
            }
        }
    }
}

 

7. 실습 결과

You exceeded your current quota, please check your plan and billing details. 현재 할당량을 초과했습니다. 요금제 및 결제 세부정보를 확인하세요.

ChatGPT 질문 결과를 보려면 결제가 필요한 듯 하다.

결제 링크 : https://platform.openai.com/account/billing/overview

+ Recent posts