Git Product home page Git Product logo

gpt-author's People

Contributors

mshumer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gpt-author's Issues

Invalid Character?

I am having an issue with hyphens for some reason... the code generated the hyphen and then said it is invalid. I am trying a workaround by stating not to use hyphens in the writing style area.

image

Key content error

Hello. I haven't been able to generate a single book. I get this particular error at various stages of generation. In this screenshot, i got it after the book was compiled. Other times I get it after 5 chapters,
Key_error
or 10, other times right at the beginning.
Most of the times though, after generating the last chapter. I get no output

Rrrirjrjtjtjrjejrjtjen

Создатель
Правит всей Вселенной
Наставляет Высших Существ на путь истинный.
Он лишь наставляет, но ни во что не вмешивается.
Все существа имеют свободную волю, их создали не для подчинения.
Они должны сами избрать свой путь..
———————————————————————
{ Тем временем
Далеко во Вселенной
В галактике, под названием - Найто Кога.
Есть планета, под названием - Оскал. }
[ Шёл 1265 год.. ]
Одни авантюристы ходили по миру в поисках затерянных гробниц, ценных артефактов и сокровищ. В этой группе авантюристов находилась девушка, её звали Талия.
Она довольно юная девушка, ей нет и восемнадцати лет. Явлеется большой поклонницей древней магии и обожающая приключения. Ростом явно ниже среднего и стройного телосложения, у неё бурый цвет волос, также является обладательницей прекрасных серых глаз.
Она со своим дядей, а также лидером отряда авантюристов - Бруком, шла к новым неизведанным землям.
Для того чтобы попасть в эти земли, они использовали ранее нигде не виданную карту. Которую купили у одной старушки на рынке. Никто не видел эту старушку и не знает кто она, но может купленная у неё карта на самом деле поможет.
И вот, они почти добрались до ранее никому неизвестной гробницы. Пройдя ещё немного её можно было увидеть издалека. И она казалась не такой, как они себе представляли.
Она выглядела как не очень большая гробница, в некоторых местах разваленная. Была покрыта серой и растениями, которые просочились через щели.
— Не нравится мне это. Чувствуется какой-то подвох в этом. Та старушка слишком подозрительная, она явно чего-то недоговорила. Иначе почему за место куда она отправила запрос, платили так много. Да и отправилось туда довольно много людей, но мы никого из них не встречали по пути. — сказал Брук
— Ой, да ладно тебе — ответила Талия.
— Нам ли не привыкать к трудностям? Да и тем более, раз она платит, то нам не нужно задавать вопросов.
Брук посмотрел на неё
— Так то оно так, но я потратил на эту карту последние деньги. Хотелось бы хоть что-то с этого заиметь, а в итоге мы все пришли посмотреть на разваленный пережиток прошлого.
С улыбкой отвечает она дяде — Ты всё равно нечестным путём эти деньги достал, тебе ли переживать.
Пройдя немного в тишине, Брук вздохнул и заговорил своим басистым голосом.
— Жаль, что платят только после выполнения исследовательской экспедиции. Ну, хоть что-то.
Похлопав его по плечу, племянница решила его немного взбодрить.
— Ладно — сказала Талия.
— Давайте проверим оружие и припасы и пойдём внутрь. А то мало ли что нас там ждёт. Не стоит судить по первому взгляду.
Талия, Брук и остальные авантюристы начинают проверять припасы.
— Что это за чертовщина! — крикнул эхом Брук.
Этот крик заставил дёрнуться всех авантюристов поблизости, даже Талию, от неожиданности.
— Что случилось капитан? — спрашивает худощавый и высокий мужчина средних лет.
— Зилий, я тебе как своему заместителю поручил подготовиться к этой экспедиции. Так ответь же мне, почему у нас так мало продовольствия, магических припасов и оружия? – гневается капитан на своего заместителя.
— Особенно это касается, если миссия выглядит как обычный запрос по исследованию неизведанной территории, но мы же не можем знать всего что с нами случится в этой гробнице. Тем более, если нам за это должны заплатить крупную сумму. Не стыдно ли тебе, пренебрегать моими указаниями?!
— Ну это.. как бы сказать.. — испуганно и одновременно встревоженно Зилий смотрит по сторонам.
— Ну, давай говори!
— Всё дело в том, что все наши припасы, они у нас есть..
— Что значит есть?.. — не успев договорить и дойти до Зилия, разъярённого Брука с разных сторон начинают окружать его же авантюристы.
— Всё дело в том — усмехается Залий и почувствовал уверенность, после того как страх стал утихать, продолжил.
— Что у нас есть информация из одного источника, будто в этой гробнице есть очень много богатств, но и это не самое главное. Говорят здесь есть артефакт, тот самый созданный Высшими Существами. Я конечно не верю в Создателя, но если на нашей планете находится артефакт, и что самое интересное, он находится в гробнице которая прямо перед нами, это начинает делать меня верующим.
Раскинув руки в стороны, он начинает смеяться что есть мочи, изображая большую радость своим змеиным лицом.
— Если артефакт действительно там, то это поможет мне в достижении поставленных целей. Я порабощу эту планету, стану для неё новым Богом. И в конечном итоге, стану одним из Высших Существ.
— Всё что мне нужно сделать, это найти артефакт под названием Глаз Бога. Не знаю что именно это обозначает, но само название уже звучит великолепно.
Авантюристы всё ещё окружают своего капитана со своей племянницей. Пока Зилий рассказывал им о своих тайных заговорах и планах, а также о том что ему говорили про эту самую гробницу и артефакт. Талия и Брук всё плотнее и плотнее прижимались к друг другу спиной, так как авантюристы сжимали их в кольцо. И наконец, они были полностью окружены.
— Ну, что делать будем? Как насчёт перерезать всех предателей? — спросил Брук, доставая из под пояса нож.
— Это все твои идеи? — толкает она его в спину.
— А у тебя есть другое предложение?
— Ну..
Решив ей ответить, сейчас уже он толкает её в спину.
— Не тяни резину!
— Давай врассыпную! — прошептала она ему под ухо.
— Думаешь прокатит?
— Не переживай, ты и на том свете сможешь грабить людей.
ХАХАХ
Засмеялся Брук.
— Что за грубость? Кто тебя такой воспитывал?
Они оба засмеялись и долго не думая начали разбегаться в разные стороны, стараясь сбить с толку противников.
Дядя старался прорваться сквозь толпу людей, при этом размахивая своим ножом, он успел ранить несколько авантюристов. Увидев сопротивление перед собой, к нему подбежали другие предатели, один из них даже забежал сзади. Брук почувствовал угрозу решил защитить свой тыл, но не успев замахнуться ножом, авантюрист атаковал его сзади и сразу же ранил прямо в живот, попытавшись что-то ответить резкая боль пронзила его. Дальше, другие авантюристы атаковав его с разных сторон, и нанесли ему ещё несколько ножевых ранений. Капитан остался жив, но дальше бежать не мог, свалившись без сил, он потерял сознание. Развернувшись и увидев это зрелище, Талия впала в шок. На эмоциях она закричала и её охватил шок.
— Ах, вы суки! Всех перебью!
Тут на неё бежит авантюрист с мечом, замахнувшись он собирается ударить. Она еле успела увернуться влево, как меч пролетает прямо перед её лицом, но не задев кожу. Девушка не растерялась, вытащила быстро из под пояса нож и подпрыгнув, помогая второй рукой воткнула его нападающему прямо в глаз. Двигаясь прямо, она хочет всеми силами спасти Брука и если потребуется, пожертвовать своей жизнью. Но тут прямо перед ней возник Зилий.
— Не сбежишь сучка!
— Пошёл ты! — кричит она, побежав прямо на него с целью убить. Но тут, один авантюрист атаковал её при помощи лука, стрела полетела так быстро, что девушка не успела среагировать. Попав в ногу, стрела прошла почти насквозь и от резкой боли Талия упала. Несмотря на острую боль, она собралась и всеми силами постаралась надломить стрелу, чтобы вытащить её из своей ноги. Но не дав закончить начатое, авантюристы окружили её.
— Не держи на меня зла, мир бывает жесток и не всё происходит как в сказках. По крайней мере, счастливого конца тебе с дядей точно не видать. — сказал с ухмылкой Зилий. — Хотя, ты всё ещё можешь исправить свою ситуацию. Может договоримся?
— Не дождёшься — крикнула с болью девушка.
— Знаешь, а ты бы могла вылечить серьёзные ранения своего дяди — указывает он на своего капитана, который медленно умирает от потери большого количества крови.
— Ты..ты врёшь..
— Думаешь? — ответил он со змеиным выражением лица.
— Мы ведь идём туда за Глазом Бога, говорят этот артефакт умеет исполнять любые желания. От лечения и усиления тела, до становления бессмертным и всезнающим Богом. Ты в праве выбрать, умрёте ли вы сейчас или же у вас будет хоть какой-то шанс на спасение. Ну, если я конечно же не вру.
— Зачем ты тогда напал на нас, если тебе нужен только этот артефакт?
— Всё не так просто как кажется. Ведь для того чтобы этот артефакт исполнил желание, нужна жертва, а добровольно жизнь никто отдавать не хочет.
Талия хочет что-то сказать, но Зилий тут же перебивает её.
— Если говорить коротко, мы выбрали твоего дядю не просто так. Он был слишком жесток к нам, к каждому авантюристу капитан относился безразлично. Ему вечно что-то не нравилось, постоянно критиковал нас и единственное что волновало нашего славного лидера, это его племянница. Ты ведь знаешь как это бывает, с каждым днём мириться с таким отношением, было всё труднее и труднее. Поэтому мы и решили принести его в жертву, тем самым и артефакт добыть и избавив нас от этого проблемного руководителя. Но сейчас ситуация немного изменилась, ты убила нескольких наших, они идеально подходят для жертвы. Одно из желаний можно потратить на восстановление Брука — улыбается Зилий.
— Но зачем вам я?
— Ты нужна нам, потому что у тебя есть карта и ты в ней разбираешься. Также, наш картограф находится в довольно плачевном состоянии и пока не может провести нас по гробнице. Мы воины, живём битвами но в понимании карты не понимаем много, да и ориентироваться в местности слегка затруднительно. Поэтому, почему бы не предоставить это знающему человеку.
— Так что, ты пойдёшь с нами, ты согласна? — спросил Зилий.
Талия думает..
— Если есть хоть малейший шанс мне и дяде выбраться отсюда живыми, то почему бы не воспользоваться этой возможностью. Все же это лучше, чем просто умереть здесь.
Взяв карту в руки и ещё раз внимательно всё извучив, девушка показала дорогу.
— Отлично, ты сделала верное решение. И теперь прежде чем мы продолжим путь, давайте обработаем ваши раны. — произносит это Зилий явно чувствуя что всё идёт так, как он задумал.
Через некоторое время они подошли к гробнице и теперь, только один шаг останавливает их от входа внутрь.
— Странно — говорит Талия осматриваясь. Нет никаких ловушек, ни простых ни даже магических. Это слишком необычно.
Все останавливаются.
—"Теперь гробницу можно рассмотреть в своё удовольствие. Вблизи она кажется намного больше чем издалека, но она всё также разваленная и заросшая какими-то неизвестными растениями. Конечно не стоит судить по первому взгляду, ведь в нашем мире даже червь может быть смертельно опасным. А с этой гробницей явно что-то не так" — подумала про себя Талия.
Пройдя чуть дальше, они прошли решётку которая окружала участок земли где стояли авантюристы, сама же местность на которой они находились, была покрыта поросший густой травой. Внутри ограды растёт также несколько высоких деревьев. В противоположных концах виднеются могилы около которых находятся два круглых цилиндрических камня, напоминающих небольшие жернова. В центре одного из них, наверху камня, видно четырёхугольное отверстие и хорошо заметная трещина в камне. К этому камню привязан воткнутый в землю высокий шест. На вершине шеста находится золотой, или позолоченный, диск с надписью на непонятном языке, явно напоминающий рипиду. Всё это сооружение обнесено высокой каменной стеной, в которой сделаны несколько дверей и окон.
— Я помню, что сюда много кто отправлялся. Но здесь нет никаких следов присутствия других людей, даже намёка на это. Будто до нас никто здесь не бывал, так ещё и на мировых картах эта гробница не значится. Всё что у нас есть, эта карта полученная от пожилой женщины. Лучше быть на стороже.
Эти мысли посещали не только Талию, но и всех оставшихся авантюристов. Но все они знают зачем пришли, отступать уже было некуда. Готовые ко всему, группа продолжила свой путь. Как только авантюристы вошли внутрь, им кажется что гробница внутри выглядит совсем иначе, не только тем как она внешне изменилась, но и по размерам она стала, будто намного больше места чем снаружи.
—"Магия что-ли какая" — подумала Талия, но постаралась отвлечь себя от этих мыслей, ведь ей сейчас совсем не до этого
— Так. И куда нам дальше идти. Такое ощущение, что здесь можно заблудиться. Пожалуйста многоуважаемый картограф, доведите нас — говорит усмешливо Зилий, ещё и саркастически поклонился.
Все вантюристы уставились на Талию, ожидая что она направит их в нужном направлении. Видимо только она сможет указать путь.

Llama Support

Now that we have Llama3. Shall we consider supporting it?

Easiest is probably connected through toolkit api like ollama using it's SDK

I'd be happy to spin off a PR soon! 😄

InvalidRequestError: The model `gpt-4-32k`

I am not sure if this is the correct place to post this; if not, I apologize in advance. I like trying out different AI tools, and currently, I am experimenting with GPT_Author. I have followed all the steps and read as much material as I can find, but I still can't get it to work. I have paid for GPT-4 and for the GPT API. When I run GPT Author, I see the step cost for each section, but in the end, I encounter an error. I am not a programmer, so this is very confusing.

InvalidRequestError Traceback (most recent call last) Cell 7 line 5

3 num_chapters = 15

4 writing_style = "Clear and easily understandable, similar to a young adult novel. Lots of dialogue." ---->

5 novel, title, chapters, chapter_titles = write_fantasy_novel(prompt, num_chapters, writing_style, claude_true)

7 # Replace chapter descriptions with body text in chapter_titles

8 for i, chapter in enumerate(chapters):

Cell 7 line 2

266 chapter_titles = ast.literal_eval(storyline)

269 novel = f"Storyline:\n{storyline}\n\n" -->

271 first_chapter = write_first_chapter(storyline, chapter_titles[0], writing_style.strip(), claude_true) 272 print('first chapter written')

273 novel += f"Chapter 1:\n{first_chapter}\n"

Cell 7 line 1

135 response = openai.ChatCompletion.create(

136 model="gpt-4",

137 messages=[ (...)

140 ]

141 )

143 print_step_costs(response, "gpt-4") -->

145 improved_response = openai.ChatCompletion.create(

...

766 rbody, rcode, resp.data, rheaders, stream_error=stream_error

767 )

768 return resp InvalidRequestError: The model gpt-4-32k does not exist or you do not have access to it. Learn more: https://help.openai.com/en/articles/7102672-how-can-i-access-gpt-4.

Rate Limit Issue 10KTPM-200RPM

Looking to make some adjustments to create a wait loop to check based on Rate Limit for the specific models. I have been getting an issue when trying to run and hit the limits.

If we can incorporate a way to put a wait/pause loop type check for this type of error so the notebook can continue without failing when hitting the limit.

I will be testing some options but wanted to start this thread to get others input.

Different Language?

I find it very beautiful what you have created, is it also possible to create stories in other languages like Dutch? If so, how can I do this? Thank you very much.

KeyError always at Chapter 2

Hi. Just starting out with this and I have been exploring a range of options. Initially I got the GPT-4-32k error, so I changed all of those to GPT-4. I am on a well paid GPT account, not a free one. For some reason, I keep getting this error each time I run the cells and I am not sure what I am doing wrong.

Step Cost (OpenAI): 0.08856
generated plots
Step Cost (OpenAI): 0.0936
selected best plot
Step Cost (OpenAI): 0.07782
plot improved
Step Cost (OpenAI): 0.001497
title generated
Generating storyline with chapters and high-level details...
Step Cost (OpenAI): 0.10764000000000001
Step Cost (OpenAI): 0.14016
storyline generated
Step Cost (OpenAI): 0.14730000000000001
Step Cost (OpenAI): 0.14730000000000001
first chapter written
Writing chapter 2...

KeyError Traceback (most recent call last)
in <cell line: 5>()
3 num_chapters = 22
4 writing_style = "Clear and easily understandable, hard science fiction. Lots of dialogue."
----> 5 novel, title, chapters, chapter_titles = write_fantasy_novel(prompt, num_chapters, writing_style, claude_true)
6
7 # Replace chapter descriptions with body text in chapter_titles

1 frames
in write_fantasy_novel(prompt, num_chapters, writing_style, claude_true)
277 print(f"Writing chapter {i+2}...") # + 2 because the first chapter was already added
278
--> 279 chapter = write_chapter(novel, storyline, chapter_titles[i+1])
280 try:
281 if len(str(chapter)) < 100:

in write_chapter(previous_chapters, plot, chapter_title, claude)
176 response = requests.post(url, headers=headers, json=data)
177
--> 178 print_step_costs_anthropic(prompt, response.json()['completion'])
179
180 return 'Chapter ' + response.json()['completion'].strip().split('```')[0].strip()

KeyError: 'completion'

anthropic cost

hi, I have a question, does antrophic need $5 to make it work?

error 400

 in generate_text(prompt, model, max_tokens, temperature)
     20     response = requests.post("https://api.anthropic.com/v1/messages", headers=headers, json=data)
     21     print (response)
---> 22     response_text = response.json()['content'][0]['text']
     23     return response_text.strip()
     24 

KeyError: 'content'

400 error pops up in the generate_text function in the request

unterminated string literal

in write_fantasy_novel
chapter_titles = ast.literal_eval(storyline)

Certainly, here's a more polished and expanded version of the storyline for "$$$," presented in the same list of dictionaries format as requested:
^
SyntaxError: unterminated string literal (detected at line 1)

Feature ask for prompt develop

Would be great to propose an idea and let it improve "a certain amount of time" and choose the best, or even better, choose to reiterate the prompt suggestions base on it, and ask for modification, that way it would be much easier to generate a prompt, as of for now you should use another AI or write a good prompt yourself

Writing Style

Hi,
this is such a great tool, thank you for sharing!

I'm not in development and just use trial and error to figure things out here... It works well so far.
I tried to change the style "fantasy" and replaced it anywhere it shows up with other writing styles but it somehow keeps writing fantasy style. I guess the style is implemented somewhere 'deeper' (sorry, I'm lacking programming terms).
Is there a way to make the style open to change?
If this is not in your intention with this tool please ignore.
Thanks,
Tina

Chunking

I was looking at forking this and implementing Chunking as most of us don't have access to the GPT-4-32K option as they stopped offering it weeks ago. Updating to include some sort of chunking would def help. Thoughts?


def make_openai_request(prompt, tokens=500):
    model = "gpt-4"  # Update this to the correct GPT-4 model identifier since we can't use 32k...
    error_retry_count = 0
    
    while error_retry_count < 3:
        try:
            print(f"Making API request for prompt: {prompt[:50]}...")
            
            # Chunk the prompt into smaller pieces
            chunk_size = 500  # Adjust as needed to stay within token limit
            responses = []
            
            for start in range(0, len(prompt), chunk_size):
                end = start + chunk_size
                response = openai.ChatCompletion.create(
                    model=model,
                    messages=[{
                        "role": "system",
                        "content": "You are a helpful assistant."
                    }, {
                        "role": "user",
                        "content": prompt[start:end]
                    }],
                    max_tokens=tokens
                )
                responses.append(response)

            # Combine responses from all chunks
            combined_response = ""
            for response in responses:
                if response and response['choices']:
                    combined_response += response['choices'][0]['message']['content'].strip()
                else:
                    print("API response empty. Retrying...")
                    error_retry_count += 1
                    break
            
            if combined_response:
                print(f"API request successful for prompt: {prompt[:50]}")
                return combined_response

        except Exception as e:
            print(f"An error occurred during the API call: {e}")
            error_retry_count += 1
            time.sleep(2)  # Wait before retrying

    print("Failed to get a successful API response after 3 tries.")
    return None


Suggestion: Add a 'Dicussion' section to the repository

To facilitate exchanges and questions between users, why not add a 'Discussion' section to the repository.
This would make it possible to leave only the real bugs identified in the 'Issues' section, rather than the basic questions about operation that we all have.

book help pls

if anyone has free time and he has figured out the work of this program can you help me with writing a book promt I will discount. telegram if you want to clarify something @alakir229

An update to the OpenAI access API version is required

An update to the OpenAI access API version is required

When trying to run gpt-autor in Colab mode, the APIRemovedInV1 error is displayed during code execution:

APIRemovedInV1:

You tried to access openai.ChatCompletion, but this is no longer supported in openai>=1.0.0 - see the README at https://github.com/openai/openai-python for the API.

You can run openai migrate to automatically upgrade your codebase to use the 1.0.0 interface.

Alternatively, you can pin your installation to the old version, e.g. pip install openai==0.28

A detailed migration guide is available here: openai/openai-python#742

Idea: Gpt-Co-Author

We could write our ideas out in a sloppy, grammatically incorrect manner and provide some direction. The co-author adjusts, corrects, and adds as little or as many details as the user prompts - as well as much creativity the user gives to the co-author gpt.

Issues: It's too descriptive and uses too many "academic" words. It needs to feel more authentic. The dialogue is extremely lacking.

Support for more open source model

Litellm is one open source project which helps projects like this to connect with different 100+LLMs easily so what I was thinking was that is there any possibility of its addition to this project so that with open source model people can generate novels too :-)) and with less or zero cost

Error

APIRemovedInV1 Traceback (most recent call last)
in <cell line: 5>()
3 num_chapters = 10
4 writing_style = "Clear and easily understandable, similar to a young adult novel. Lots of dialogue."
----> 5 novel, title, chapters, chapter_titles = write_fantasy_novel(prompt, num_chapters, writing_style, claude_true)
6
7 # Replace chapter descriptions with body text in chapter_titles

2 frames
in write_fantasy_novel(prompt, num_chapters, writing_style, claude_true)
250
251 def write_fantasy_novel(prompt, num_chapters, writing_style, claude_true=False):
--> 252 plots = generate_plots(prompt)
253 print('generated plots')
254

in generate_plots(prompt)
43
44 def generate_plots(prompt):
---> 45 response = openai.ChatCompletion.create(
46 model="gpt-4",
47 messages=[

/usr/local/lib/python3.10/dist-packages/openai/lib/_old_api.py in call(self, *_args, **_kwargs)
37
38 def call(self, *_args: Any, **_kwargs: Any) -> Any:
---> 39 raise APIRemovedInV1(symbol=self._symbol)
40
41

APIRemovedInV1:

You tried to access openai.ChatCompletion, but this is no longer supported in openai>=1.0.0 - see the README at https://github.com/openai/openai-python for the API.

You can run openai migrate to automatically upgrade your codebase to use the 1.0.0 interface.

Alternatively, you can pin your installation to the old version, e.g. pip install openai==0.28

A detailed migration guide is available here: openai/openai-python#742
how to fix this

KeyError: 'content'

When trying to generate a book using api claude 3 in google colab on chapter 15 it gives an error. What to do?

Requirement already satisfied: EbookLib in /usr/local/lib/python3.10/dist-packages (0.18)
Requirement already satisfied: lxml in /usr/local/lib/python3.10/dist-packages (from EbookLib) (4.9.4)
Requirement already satisfied: six in /usr/local/lib/python3.10/dist-packages (from EbookLib) (1.16.0)
Enter the desired writing style: exciting and mystical, with elements of science fiction and philosophy; - full of surprises, leading the reader through a series of complex resolutions and mysteries; - dramatic, with deeply developed characters facing difficult moral choices; - emotional, emphasizing human relationships and their importance in a world of technological wonders; - written with a high intellectual load, in order to stimulate the reader to reflect on the nature of human existence and the future of civilization.
Enter a high-level description of the book: In the year 2182 on the A-class space station of the planet Omega 8, Alex faces an unexpected twist of fate when he finds an infant at his door. The Law of Interchangeability: In a world where aging is halted and consciousness can be transferred into androids, childbirth is strictly controlled by the Empire to keep the population stable. The Dilemma: Alex, who has never had children and has no right to have them, decides to enlist the help of a friend, the station chief, to decide what to do with a child he has found.
Enter the number of chapters: 20
Generating plot outline...
Plot outline generated.
Generating chapter 1...
Chapter 1 generated.
Generating chapter 2...
Chapter 2 generated.
Generating chapter 3...
Chapter 3 generated.
Generating chapter 4...
Chapter 4 generated.
Generating chapter 5...
Chapter 5 generated.
Generating chapter 6...
Chapter 6 generated.
Generating chapter 7...
Chapter 7 generated.
Generating chapter 8...
Chapter 8 generated.
Generating chapter 9...
Chapter 9 generated.
Generating chapter 10...
Chapter 10 generated.
Generating chapter 11...
Chapter 11 generated.
Generating chapter 12...
Chapter 12 generated.
Generating chapter 13...
Chapter 13 generated.
Generating chapter 14...
Chapter 14 generated.
Generating chapter 15...

KeyError Traceback (most recent call last)
in <cell line: 172>()
170
171 # Generate the book
--> 172 plot_outline, book, chapters = generate_book(writing_style, book_description, num_chapters)
173
174 title = generate_title(plot_outline)

1 frames
in generate_text(prompt, model, max_tokens, temperature)
31 }
32 response = requests.post("https://api.anthropic.com/v1/messages", headers=headers, json=data)
---> 33 response_text = response.json()['content'][0]['text']
34 return response_text.strip()
35

KeyError: 'content'

Issue with OpenAI version

Hi, seems to be an issue with OpenAi v<1.00. Is it just a case of migrating to 1.00 and running the script?

KeyError: 'content' in Claude_Author.ipynb

I'm using the newest version (https://github.com/mshumer/gpt-author/blob/main/Claude_Author.ipynb)

Added my API keys, ran the cell, filled out writing style, content, and number of chapters.
After the 10 chapters have been generated, it always results in this error

Generating plot outline...
Plot outline generated.
Generating chapter 1...
Chapter 1 generated.
Generating chapter 2...
Chapter 2 generated.
Generating chapter 3...
Chapter 3 generated.
Generating chapter 4...
Chapter 4 generated.
Generating chapter 5...
Chapter 5 generated.
Generating chapter 6...
Chapter 6 generated.
Generating chapter 7...
Chapter 7 generated.
Generating chapter 8...
Chapter 8 generated.
Generating chapter 9...
Chapter 9 generated.
Generating chapter 10...
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
[<ipython-input-2-c4c8d1aecfd2>](https://localhost:8080/#) in <cell line: 172>()
    170 
    171 # Generate the book
--> 172 plot_outline, book, chapters = generate_book(writing_style, book_description, num_chapters)
    173 
    174 title = generate_title(plot_outline)

1 frames
[<ipython-input-2-c4c8d1aecfd2>](https://localhost:8080/#) in generate_text(prompt, model, max_tokens, temperature)
     31     }
     32     response = requests.post("https://api.anthropic.com/v1/messages", headers=headers, json=data)
---> 33     response_text = response.json()['content'][0]['text']
     34     return response_text.strip()
     35 

KeyError: 'content'

FileNotFoundError: [Errno 2] No such file or directory: '/content/cover.png'

This is my first use of Jupyter :)
I'm using Jupyter locally, on my Windows.

I've received such error:

---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
Cell In[14], line 13
     10     chapter_titles[i] = {chapter_number_and_title: chapter}
     12 # Create the cover
---> 13 create_cover_image(str(chapter_titles))
     15 # Create the EPUB file
     16 create_epub(title, 'AI', chapter_titles, '/content/cover.png')

Cell In[2], line 51, in create_cover_image(plot)
     48 data = response.json()
     50 for i, image in enumerate(data["artifacts"]):
---> 51     with open(f"/content/cover.png", "wb") as f: # replace this if running locally, to where you store the cover file
     52         f.write(base64.b64decode(image["base64"]))

File ~\Documents\Python\p3_10\lib\site-packages\IPython\core\interactiveshell.py:284, in _modified_open(file, *args, **kwargs)
    277 if file in {0, 1, 2}:
    278     raise ValueError(
    279         f"IPython won't let you open fd={file} by default "
    280         "as it is likely to crash IPython. If you know what you are doing, "
    281         "you can use builtins' open."
    282     )
--> 284 return io_open(file, *args, **kwargs)

FileNotFoundError: [Errno 2] No such file or directory: '/content/cover.png'

Of course - i've put my Stability Key in stability_api_key variable, and make a "content" directory before run (in the same directory as the script AND one level higher). There are no pictures In my Stability history also (and i can manually create pictures there).

.epub not found

after generation i can`t find where epub is saved or saved at all :D waste of my tokens damn :D

Cannot find the generated book

I cannot find the generated book I've looked in the files for the colab and cannot locate it and my missing something I've been able to work through all of the errors and it seems to complete the book it says it completes chapter 15

KeyError: 'completion' upon beginning chapter 2

Upon beginning to write chapter 2 I get this error output re: Completion, did anyone else run into this?

I'm set to 5 chapters, using model gpt-3.5-turbo-16k

`KeyError Traceback (most recent call last)
in <cell line: 5>()
3 num_chapters = 5
4 writing_style = "Clear and easily understandable, similar to a young adult novel. Lots of dialogue."
----> 5 novel, title, chapters, chapter_titles = write_fantasy_novel(prompt, num_chapters, writing_style, claude_true)
6
7 # Replace chapter descriptions with body text in chapter_titles

1 frames
in write_chapter(previous_chapters, plot, chapter_title, claude)
176 response = requests.post(url, headers=headers, json=data)
177
--> 178 print_step_costs_anthropic(prompt, response.json()['completion'])
179
180 return 'Chapter ' + response.json()['completion'].strip().split('```')[0].strip()

KeyError: 'completion'`

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.