Created
May 11, 2023 09:09
-
-
Save SidJain1412/205f3e9ab54c24144599ec625591bd5b to your computer and use it in GitHub Desktop.
Simple example using FastAPI and OpenAI to create an API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from fastapi import FastAPI, Query | |
import openai | |
import os | |
import sys | |
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "") | |
if not len(OPENAI_API_KEY): | |
print("Please set OPENAI_API_KEY environment variable. Exiting.") | |
sys.exit(1) | |
openai.api_key = OPENAI_API_KEY | |
app = FastAPI( | |
title="Simple API", | |
) | |
def get_response_openai(prompt): | |
try: | |
prompt = prompt | |
response = openai.ChatCompletion.create( | |
model="gpt-3.5-turbo", | |
n=1, | |
top_p=1, | |
frequency_penalty=0, | |
presence_penalty=0, | |
messages=[ | |
{"role": "system", "content": "You are an expert creative marketer. Create a campaign for the brand the user enters."}, | |
{"role": "user", "content": prompt}, | |
], | |
) | |
except Exception as e: | |
print("Error in creating campaigns from openAI:", str(e)) | |
return 503 | |
return response["choices"][0]["message"]["content"] | |
@app.get( | |
"/campaign/", | |
tags=["APIs"], | |
response_model=str, | |
) | |
def campaign(prompt: str = Query(..., max_length=20)): | |
return get_response_openai(prompt) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment