The openAI UI will directly insert text into a word file if I ask it to. How do I get the same functionality from the API?
I assume you refer to ChatGPT when you write “OpenAI UI”? To create a Word document, ChatGPT relies on Code Interpreter and writes a Python script that involves creating a Word document and inserting the text.
Basically, in order to replicate the functionality via API you need to add the same steps to your script using a library such as python-docx.
Yes, that’s what I mean thank you.
I’m really just trying to get it to insert some text into the text of a word document and return the total text. Do you have any suggestions on how to prompt that?
Well, as said, we need to distinguish the two cases. In ChatGPT, the prompt would be as simple as the following. You would then be provided with a link to download the file:
Write a short text about […]. Insert the text into a Word document and make it available for download.
If you are using the API, you need to include two steps in your script. The initial OpenAI API call to generate your text of choice, followed by the step to insert the text into the Word document.
For the latter, the basic script would look as follows whereby random_text in this case would be the output created by the OpenAI API call (for the record, I just relied on ChatGPT to create this basic example real quick).
Obviously, you can make this a lot more complex but hopefully this should give you the idea:
from docx import Document
doc_random_text = Document()
doc_random_text.add_heading('Random Text', level=1)
random_text = """
As the sun dips below the horizon, the city lights flicker to life. Cars buzz along the streets, their headlights carving paths through the growing darkness. A soft breeze carries the sounds of distant laughter and the aroma of street food, hinting at the vibrant nightlife awakening in the heart of the city.
"""
doc_random_text.add_paragraph(random_text)
random_text_file_path = "C:/Users/UserName/Desktop/Random_Text.docx"
doc_random_text.save(random_text_file_path)
You can reference langchain ReAct and autogen, both use chatgpt to generate code to do actions, such as insert text into a word file.
You can also use write a function call to do the inserting!