Skip to content

Instantly share code, notes, and snippets.

@buanzo
Last active October 19, 2023 17:31
Show Gist options
  • Save buanzo/2f3164b187e1b3e14f289195a7e58477 to your computer and use it in GitHub Desktop.
Save buanzo/2f3164b187e1b3e14f289195a7e58477 to your computer and use it in GitHub Desktop.
# This code snippet shows one way we could use gpt inside a Jinja2 template
# to hack-around the context limitations. Have fun! And remember, the ART is the prompt...
# MAKE SURE you modify the 'set titulo' (titulo is title in spanish)
# Author: Arturo "Buanzo" Busleiman <[email protected]>
import os
import openai
import json
from jinja2 import Template
# Set up OpenAI API authentication
openai.api_key = os.environ["OPENAI_API_KEY"]
# Define your template using Jinja2 syntax
# In this example, the template includes a title, an abstract/scoop,
# Table of Contents and then content. You may create markdown, html, reStructuredText, etc.
template = Template("""
{% set titulo = "Super useful Python Libraries" %}
{% set toc = gpt3(titulo, type="Array", len=5, random=True, lang='Spanish') %}{{ titulo }}
{% set abstract = gpt3("Article scoop about {}: {}".format(titulo,','.join(toc)), lang='Spanish', type='Content') %}
TITULO: {{ titulo }}
ABSTRACT: {{ abstract }}
Table of contents
-----------------
{% for item in toc %}
* {{ item }}
{% endfor %}
{% for item in toc %}
{{ item }}
{% set content = gpt3('{}: {}'.format(article_object,item), type='Content', lang='Spanish') %}
{{ content }}
{% endfor %}
""")
# Define a function to call the OpenAI API
def gpt3(prompt, **kwargs):
prompt = prompt.strip()
# Adapt response to whatever content-type user requires
if kwargs['type'] == 'Array':
newprompt = f"Provide a python-compatible one-dimensional json response for: {prompt}."
elif kwargs['type'] == 'Content':
newprompt = f"Write content for an article section about {prompt}."
lang = None
if 'lang' in kwargs:
lang = kwargs['lang']
newprompt += f"Respond in {lang}."
cant = None
if 'len' in kwargs:
cant = kwargs['len']
newprompt += f"Provide only {cant} items."
response = openai.Completion.create(
engine="text-davinci-003",
prompt=newprompt,
max_tokens=2048,
n=1,
stop=None,
)
raw_response = response.choices[0].text.strip()
respuesta = None
# Now adapt response to whatever content-type user requested:
if kwargs['type'] == 'Array':
respuesta = json.loads(response.choices[0].text.strip())
elif kwargs['type'] == 'Content':
respuesta = response.choices[0].text.strip()
return respuesta
# Render the completed template and output it to the command prompt
completed_template = template.render(gpt3=gpt3)
print(completed_template)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment