Package: thinkgpt
ThinkGPT 🧠🤖ThinkGPT is a Python library aimed at implementing Chain of Thoughts for Large Language Models (LLMs), prompting the model to think, reason, and to create generative agents.
The library aims to help with the following:solve limited context with long memory and compressed knowledgeenhance LLMs' one-shot reasoning with higher order reasoning primitivesadd intelligent decisions to your code baseKey Features ✨Thinking building blocks 🧱:Memory 🧠: GPTs that can remember experienceSelf-refinement 🔧: Improve model-generated content by addressing criticsCompress knowledge 🌐: Compress knowledge and fit it in LLM's context either by anstracring rules out of observations or summarize large contentInference 💡️: Make educated guesses based on available informationNatural Language Conditions 📝: Easily express choices and conditions in natural languageEfficient and Measurable GPT context length 📐Extremely easy setup and pythonic API 🎯 thanks toDocArrayInstallation 💻You can install ThinkGPT using pip:pipinstallgit+https://github.com/alaeddine-13/thinkgpt.gitAPI Documentation 📚Basic usage:fromthinkgpt.llmimportThinkGPTllm=ThinkGPT(model_name="gpt-3.5-turbo")# Make the llm object learn new conceptsllm.memorize(['DocArray is a library for representing, sending and storing multi-modal data.'])llm.predict('what is DocArray ?',remember=llm.remember('DocArray definition'))Memorizing and Remembering informationllm.memorize(['DocArray allows you to send your data, in an ML-native way.','This means there is native support for Protobuf and gRPC, on top of HTTP and serialization to JSON, JSONSchema, Base64, and Bytes.',])print(llm.remember('Sending data with DocArray',limit=1))['DocArray allows you to send your data, in an ML-native way.']Use thelimitparameter to specify the maximum number of documents to retrieve.
In case you want to fit documents into a certain context size, you can also use themax_tokensparameter to specify the maximum number of tokens to retrieve.
For instance:fromexamples.knowledge_baseimportknowledgefromthinkgpt.helperimportget_n_tokensllm.memorize(knowledge)results=llm.remember('hello',max_tokens=1000,limit=1000)print(get_n_tokens(''.join(results)))1000However, keep in mind that concatenating documents with a separator will add more tokens to the final result.
Theremembermethod does not account for those tokens.Predicting with context from long memoryfromexamples.knowledge_baseimportknowledgellm.memorize(knowledge)llm.predict('Implement a DocArray schema with 2 fields: image and TorchTensor',remember=llm.remember('DocArray schemas and types'))Self-refinementprint(llm.refine(content="""import reprint('hello world')""",critics=['File "/Users/user/PyCharm2022.3/scratches/scratch_166.py", line 2',"  print('hello world')",'IndentationError: unexpected indent'],instruction_hint="Fix the code snippet based on the error provided. Only provide the fixed code snippet between `` and nothing else."))import re
print('hello world')One of the applications is self-healing code generation implemented by projects likegptdeployandwolverineCompressing knowledgeIn case you want your knowledge to fit into the LLM's context, you can use the following techniques to compress it:Summarize contentSummarize content using the LLM itself.
We offer 2 methodsone-shot summarization using the LLMllm.summarize(large_content,max_tokens=1000,instruction_hint='Pay attention to code snippets, links and scientific terms.')Since this technique relies on summarizing using a single LLM call, you can only pass content that does not exceed the LLM's context length.Chunked summarizationllm.chunked_summarize(very_large_content,max_tokens=4096,instruction_hint='Pay attention to code snippets, links and scientific terms.')This technique relies on splitting the content into different chunks, summarizing each of those chunks and then combining them all together using an LLM.Induce rules from observationsAmount to higher level and more general observations from current observations:llm.abstract(observations=["in tunisian, I did not eat is\"ma khditech\"","I did not work is\"ma khdemtech\"","I did not go is\"ma mchitech\"",])['Negation in Tunisian Arabic uses "ma" + verb + "tech" where "ma" means "not" and "tech" at the end indicates the negation in the past tense.']This can help you end up with compressed knowledge that fits better the limited context length of LLMs.
For instance, instead of trying to fit code examples in the LLM's context, use this to prompt it to understand high level rules and fit them in the context.Natural language conditionIntroduce intelligent conditions to your code and let the LLM make decisionsllm.condition(f'Does this represent an error message ? "IndentationError: unexpected indent"')TrueNatural language selectAlternatively, let the LLM choose among a list of options:llm.select(question="Which animal is the king of the jungle?",options=["Lion","Elephant","Tiger","Giraffe"])['Lion']You can also prompt the LLM to choose an exact number of answers usingnum_choices. By default, it's set toNonewhich means the LLM will select any number he thinks it's correct.Use Cases 🚀Find out below example demos you can do withthinkgptTeaching ThinkGPT a new languagefromthinkgpt.llmimportThinkGPTllm=ThinkGPT(model_name="gpt-3.5-turbo")rules=llm.abstract(observations=["in tunisian, I did not eat is\"ma khditech\"","I did not work is\"ma khdemtech\"","I did not go is\"ma mchitech\"",],instruction_hint="output the rule in french")llm.memorize(rules)llm.memorize("in tunisian, I studied is\"9rit\"")task="translate to Tunisian: I didn't study"llm.predict(task,remember=llm.remember(task))The translation of "I didn't study" to Tunisian language would be "ma 9ritech".Teaching ThinkGPT how to code withthinkgptlibraryfromthinkgpt.llmimportThinkGPTfromexamples.knowledge_baseimportknowledgellm=ThinkGPT(model_name="gpt-3.5-turbo")llm.memorize(knowledge)task='Implement python code that uses thinkgpt to learn about docarray v2 code and then predict with remembered information about docarray v2. Only give the code between `` and nothing else'print(llm.predict(task,remember=llm.remember(task,limit=10,sort_by_order=True)))Code generated by the LLM:from thinkgpt.llm import ThinkGPT
from docarray import BaseDoc
from docarray.typing import TorchTensor, ImageUrl

llm = ThinkGPT(model_name="gpt-3.5-turbo")

# Memorize information
llm.memorize('DocArray V2 allows you to represent your data, in an ML-native way')


# Predict with the memory
memory = llm.remember('DocArray V2')
llm.predict('write python code about DocArray v2', remember=memory)Replay Agent memory and infer new observationsRefer to the following script for an example of an Agent that replays its memory and induces new observations.
This concept was introduced inthe Generative Agents: Interactive Simulacra of Human Behavior paper.python-mexamples.replay_expand_memorynew thoughts:
Klaus Mueller is interested in multiple topics
Klaus Mueller may have a diverse range of interests and hobbiesReplay Agent memory, criticize and refine the knowledge in memoryRefer to the following script for an example of an Agent that replays its memory, performs self-criticism and adjusts its memory knowledge based on the criticism.python-mexamples.replay_criticize_refinerefined "the second number in Fibonacci sequence is 2" into "Observation: The second number in the Fibonacci sequence is actually 1, not 2, and the sequence starts with 0, 1."
...This technique was mainly implemented in thethe Self-Refine: Iterative Refinement with Self-Feedback paperFor more detailed usage and code examples check./examples.