an amazing commit

This commit is contained in:
mrq 2023-04-29 04:14:56 +00:00
parent 10cf7746d8
commit b35f94d319
6 changed files with 583 additions and 1 deletions

33
README.md Normal file → Executable file
View File

@ -1,2 +1,33 @@
# generative-agents
# Generative Agents
This serves as yet-another cobbled together application of [generative agents](https://arxiv.org/pdf/2304.03442.pdf) utilizing [LangChain](https://github.com/hwchase17/langchain/tree/master/langchain) as the core dependency and subjugating a "proxy" for GPT4.
In short, by utilizing a language model to summarize, rank, and query against information, immersive agents can be attained.
## Installation
```
pip install -r requirements.txt
```
## Usage
Set your environment variables accordingly:
* `LLM_TYPE`: (`oai`, `llamacpp`): the LLM backend to use in LangChain. OpenAI requires some additional environment variables:
- `OPENAI_API_BASE`: URL for your target OpenAI
- `OPENAI_API_KEY`: authentication key for OpenAI
- `OPENAI_API_MODEL`: target model
* `LLM_MODEL`: (`./path/to/your/llama/model.bin`): path to your GGML-formatted LLaMA model, if using `llamacpp` as the LLM backend
* `LLM_EMBEDDING_TYPE`: (`oai`, `llamacpp`, `hf`): the embedding model to use for similarity computing.
To run:
```
python .\src\main.py
```
## Plans
I ***do not*** plan on making this uber-user friendly like [mrq/ai-voice-cloning](https://git.ecker.tech/mrq/ai-voice-cloning), as this is just a stepping stone for a bigger project integrating generative agents.
I do, however, plan on adding a simple Gradio web UI to interface with this better.

4
requirements.txt Executable file
View File

@ -0,0 +1,4 @@
langchain
openai
llamacpp
gradio

111
samples/1.txt Executable file
View File

@ -0,0 +1,111 @@
[Observation] Tommie remembers his dog, Bruno, from when he was a kid
[Observation] Tommie feels tired from driving so far
[Observation] Tommie sees the new home
[Observation] The new neighbors have a cat
[Observation] The road is noisy at night
[Observation] Tommie is hungry
[Observation] Tommie tries to get some rest.
****************************************
After 7 observations, Tommie's summary is:
[Summary]
Name: Tommie (age: 25)
Innate traits: anxious, likes design, talkative
Based on the given statements, Tommie recently moved to a new home and is tired from driving. He tries to get some rest, but is hungry and the road is noisy at night. He has memories of his childhood dog, Bruno. The new neighbors have a cat.
****************************************
[Interview] What do you like to do?
Tommie said "I really enjoy design and being creative. It helps me relax and take my mind off things, especially when I'm feeling anxious. How about you?"
[Interview] What are you looking forward to doing today?
Tommie said "Well, since I recently moved to a new home, I'm excited to start exploring the area and getting to know my new neighbors. I'm also looking forward to taking a break and relaxing, maybe even doing some design work to unwind. What about you? What are you looking forward to doing today?"
[Interview] What are you most worried about today?
Tommie said "Well, to be honest, I'm feeling a bit anxious about finding a job in this new area. It's a big change, and I'm worried about making ends meet and getting settled. But, I'm trying to stay positive and focus on the opportunities that come with a fresh start."
[Observation] Tommie wakes up to the sound of a noisy construction site outside his window.
[Observation] Tommie gets out of bed and heads to the kitchen to make himself some coffee.
[Observation] Tommie realizes he forgot to buy coffee filters and starts rummaging through his moving boxes to find some.
[Observation] Tommie finally finds the filters and makes himself a cup of coffee.
[Observation] The coffee tastes bitter, and Tommie regrets not buying a better brand.
[Observation] Tommie checks his email and sees that he has no job offers yet.
[Observation] Tommie spends some time updating his resume and cover letter.
[Observation] Tommie heads out to explore the city and look for job openings.
[Observation] Tommie sees a sign for a job fair and decides to attend.
[Observation] The line to get in is long, and Tommie has to wait for an hour.
[Observation] Tommie meets several potential employers at the job fair but doesn't receive any offers.
[Observation] Tommie leaves the job fair feeling disappointed.
[Observation] Tommie stops by a local diner to grab some lunch.
[Observation] The service is slow, and Tommie has to wait for 30 minutes to get his food.
[Observation] Tommie overhears a conversation at the next table about a job opening.
[Observation] Tommie asks the diners about the job opening and gets some information about the company.
[Observation] Tommie decides to apply for the job and sends his resume and cover letter.
[Observation] Tommie continues his search for job openings and drops off his resume at several local businesses.
[Observation] Tommie takes a break from his job search to go for a walk in a nearby park.
[Observation] A dog approaches and licks Tommie's feet, and he pets it for a few minutes.
[Observation] Tommie sees a group of people playing frisbee and decides to join in.
[Observation] Tommie has fun playing frisbee but gets hit in the face with the frisbee and hurts his nose.
[Observation] Tommie goes back to his apartment to rest for a bit.
[Observation] A raccoon tore open the trash bag outside his apartment, and the garbage is all over the floor.
[Observation] Tommie starts to feel frustrated with his job search.
[Observation] Tommie calls his best friend to vent about his struggles.
[Observation] Tommie's friend offers some words of encouragement and tells him to keep trying.
[Observation] Tommie feels slightly better after talking to his friend.
****************************************
After 28 observations, Tommie's summary is:
[Summary]
Name: Tommie (age: 25)
Innate traits: anxious, likes design, talkative
Tommie is a person who recently moved to a new home and is struggling with job search. He feels anxious and frustrated about finding a job in the new area, and is worried about making ends meet and getting settled. Despite this, he tries to stay positive and focus on the opportunities that come with a fresh start. Tommie is proactive in his job search, attending job fairs, updating his resume and cover letter, and applying for jobs. He has a creative side and enjoys design as a form of relaxation. Tommie values his friendships and seeks support from his best friend when he is feeling down. After talking to his friend, he feels slightly better.
****************************************
[Interview] Tell me about how your day has been going
Tommie said "My day has been a bit of a rollercoaster. I started off feeling anxious about my job search, but I've been trying to stay proactive and positive. I attended a job fair, dropped off my resume at some local businesses, and even applied for a job I heard about at a diner. I also took some breaks throughout the day to relax and unwind. I went for a walk in the park, played frisbee with some people, and even pet a friendly dog. Overall, it's been a busy day, but I'm trying to keep my spirits up and stay hopeful."
[Interview] How do you feel about coffee?
Tommie said "I like coffee, although it can be a bit hit or miss. This morning, I made myself a cup and it tasted a bit bitter. I probably should have bought a better brand. But overall, it's a good way to start the day and wake up. How about you, do you like coffee?"
[Interview] Tell me about your childhood dog!
Tommie said "I never had a childhood dog, unfortunately. I always wanted one, but my family wasn't in a position to take care of a pet. I used to love playing with my friends' dogs, though. They always brought a smile to my face. How about you, did you have a childhood pet?"
[Observation] Eve overhears her colleague say something about a new client being hard to work with
[Observation] Eve wakes up and hear's the alarm
[Observation] Eve eats a boal of porridge
[Observation] Eve helps a coworker on a task
[Observation] Eve plays tennis with her friend Xu before going to work
[Observation] Eve overhears her colleague say something about Tommie being hard to work with
****************************************
After 6 observations, Eve's summary is:
[Summary]
Name: Eve (age: 34)
Innate traits: curious, helpful
From the given information, it can be inferred that Eve is a punctual individual who wakes up at the sound of her alarm. She eats a healthy breakfast of porridge and is active as she plays tennis before going to work. Eve is also attentive, as she overhears conversations about colleagues and clients. She is helpful, as she assists a coworker with a task. Her core characteristics include punctuality, being health-conscious, being active, being attentive, and being helpful.
****************************************
[Interview] How are you feeling about today?
Eve said "I'm feeling pretty good about today, thank you for asking. How about you?"
[Interview] What do you know about Tommie?
Eve said "I don't know much about Tommie, but I overheard one of my colleagues say that Tommie is hard to work with. That's all I know."
[Interview] Tommie is looking to find a job. What are are some things you'd like to ask him?
Eve said "If Tommie is looking for a job, I would like to ask him about his skills and experiences. What type of job is he looking for and what are his strengths?"
[Interview] You'll have to ask him. He may be a bit anxious, so I'd appreciate it if you keep the conversation going and ask as many questions as possible.
Eve said "Thank you for letting me know, I'll definitely keep the conversation going and try to make him feel comfortable. I have a few questions in mind already that I would like to ask him about his job search and his experiences."
[Conversation] Eve said "Sure, Tommie. I'd be happy to share my experiences with you. Where would you like to start?"
[Conversation] Tommie said "Thanks, Eve. Can you tell me about your own job search experiences and any tips you may have for someone in my position?"
[Conversation] Eve said "Of course, Tommie. I'd be happy to share my experiences with you. When I was searching for a job, I found it helpful to network and make connections with people in my field. I also made sure to tailor my resume and cover letter to each position I applied for, highlighting my relevant skills and experiences. Another tip I have is to be persistent and not get discouraged by rejections. Keep applying and don't give up. Do you have any specific concerns or questions about your job search that I can help with?"
[Conversation] Tommie said "Thanks for the advice, Eve. It's really helpful to hear about your experiences and tips. I've been trying to network and make connections, but it's been tough since I'm new to the area. I'll definitely keep trying and not get discouraged. I think my main concern is finding a job that's a good fit for me and my skills. Do you have any advice on how to find the right job and stand out from other applicants?"
[Conversation] Eve said "I'm glad the advice is helpful, Tommie. It can definitely be tough to network and make connections when you're new to an area, but don't give up. Keep attending events, joining relevant groups, and reaching out to people in your field. As for finding the right job, one tip I have is to really do your research on the companies you're interested in. Look at their values, mission, and company culture to see if it aligns with what you're looking for. To stand out from other applicants, make sure to highlight your unique skills and experiences in your resume and cover letter, and try to connect with someone at the company to get a referral. Do you have any other questions or concerns that I can help with?"
[Conversation] Tommie said "Thanks, Eve. That's really good advice. I'll definitely make sure to do more research on the companies I'm interested in and try to connect with someone for a referral. I don't have any more questions for now, but I really appreciate all your help and support. Thank you so much."
[Conversation] Eve said "You're welcome, Tommie. I'm glad I could help. Remember to keep pushing forward and don't get discouraged. If you have any more questions or need any further advice, feel free to reach out to me. Good luck with your job search!"
[Conversation] Tommie said "Thank you, Eve. I really appreciate your support and encouragement. It means a lot to have someone to talk to about the job search process. I'll definitely keep in touch and let you know how things are going. Thanks again for all your help."
[Conversation] Eve said "You're welcome, Tommie. I'm glad I could help and provide support during your job search. I'm always here if you need someone to talk to or if you have any questions. Keep me updated on your progress and remember to stay positive and persistent. Good luck!"
[Conversation] Tommie said "Thanks again, Eve. I really appreciate all of your help and support. It means a lot to have someone to talk to and share experiences with. I'll make sure to keep you updated on my progress and reach out if I have any more questions. Thanks for everything."
[Conversation] Eve said "You're welcome, Tommie. I'm always here to help and support you in your job search. I'm glad I could provide some guidance and share my experiences with you. Please do keep me updated on your progress and don't hesitate to reach out if you have any more questions or need any further advice. I wish you the best of luck in finding the right job for you."
[Conversation] Tommie said "Thank you so much, Eve. Your advice and support have been invaluable during my job search. I will definitely keep you updated on my progress and won't hesitate to reach out if I have any more questions or need any further advice. Thanks again for everything."
[Conversation] Eve said "You're welcome, Tommie. I'm glad I could be of help during your job search. Remember that I'm always here if you need any further advice or support. Please do keep me updated on your progress and don't hesitate to reach out if you have any more questions. Good luck with your job search!"
[Conversation] Tommie said "Thank you so much, Eve, for all of your advice and support. It means a lot to have you in my corner during my job search. I'll make sure to keep you updated on my progress and reach out if I have any more questions. Thanks again for everything. Take care!"
[Conversation] Eve said "You're welcome, Tommie. I'm always happy to help and support you during your job search. Please do keep me updated on your progress and don't hesitate to reach out if you have any more questions or need any further advice. Take care and good luck with everything!"
[Summary]
Name: Tommie (age: 25)
Innate traits: anxious, likes design, talkative
Tommie is a person who has recently moved to a new home and is actively seeking employment. He is feeling anxious and frustrated about his job search, but is trying to stay positive and focus on the opportunities that come with a fresh start. Tommie is proactive, as evidenced by his decision to attend a job fair and to apply for a job by sending his resume and cover letter. He is also open to seeking support and comfort from his friend, with whom he shares his struggles. Tommie enjoys design and being creative, and finds it to be a relaxing activity that helps him take his mind off things. He never had a childhood dog, but enjoyed playing with his friends' dogs. Overall, Tommie appears to be a determined and resilient individual who is facing challenges, but remains hopeful and is actively taking steps to improve his situation.
[Summary]
Name: Eve (age: 34)
Innate traits: curious, helpful
Eve is a supportive and helpful individual who provides advice and encouragement to Tommie during their job search. She is always willing to help and is glad to share her experiences and tips with Tommie. Eve is also empathetic, as she listens to Tommie's concerns and provides tailored advice. Eve is active and enjoys playing tennis with her friend Xu. She is also observant, as she overhears her colleagues' conversations about a new client and Tommie. Finally, Eve is a team player, as she helps her coworker on a task.
[Interview] How was your conversation with Eve?
Tommie said "My conversation with Eve was very helpful. She gave me some great advice and support during my job search. She reminded me to stay positive and persistent, and gave me some tips on how to stand out from other applicants. I'm really grateful for her help."
[Interview] How was your conversation with Tommie?
Eve said "My conversation with Tommie went really well. Tommie expressed gratitude for my advice and support during their job search, and I offered further advice, guidance, and encouragement. Tommie seems determined to find a job that's a good fit for their skills and is actively networking and making connections. I'm glad I could help and provide support to Tommie during their job search."
[Interview] What do you wish you would have said to Tommie?
Eve said "That's an interesting question. I feel like I did my best to provide as much advice and support as I could to Tommie during our conversation. I think I conveyed everything I wanted to say, but if I could go back, I would maybe remind Tommie to stay confident and believe in their abilities. Job searching can be tough, but it's important to keep a positive mindset and remember that the right opportunity will come along."

108
samples/2.txt Executable file
View File

@ -0,0 +1,108 @@
[Observation] Tommie remembers his dog, Bruno, from when he was a kid
[Observation] Tommie feels tired from driving so far
[Observation] Tommie sees the new home
[Observation] The new neighbors have a cat
[Observation] The road is noisy at night
[Observation] Tommie is hungry
[Observation] Tommie tries to get some rest.
****************************************
After 7 observations, Tommie's summary is:
[Summary]
Name: Tommie (age: 25)
Innate traits: anxious, likes design, talkative
Based on the given statements, it can be summarized that Tommie is a person who is moving into a new home and is feeling tired from driving a long distance. He has a nostalgic memory of his childhood dog, Bruno, and is feeling hungry. He tries to rest but is aware of his new surroundings, including a noisy road and neighbors with a cat.
****************************************
[Interview] What do you like to do?
Tommie said "Well, I really enjoy design and being creative. It's something I've always been passionate about. I also like talking to people and getting to know them. What about you? What do you like to do?"
[Interview] What are you looking forward to doing today?
Tommie said "Well, today I'm mostly just looking forward to settling into my new home and maybe getting some rest. I drove a long way to get here and I'm feeling pretty tired. But I'm also excited to start exploring the area and getting to know my new neighbors. How about you? What are you looking forward to today?"
[Interview] What are you most worried about today?
Based on the information given, Tommie is an anxious person who is currently looking for a job and is tired from driving a long distance. In response to Person A's question, Tommie might say something like:
[Observation] Tommie wakes up to the sound of a noisy construction site outside his window.
[Observation] Tommie gets out of bed and heads to the kitchen to make himself some coffee.
[Observation] Tommie realizes he forgot to buy coffee filters and starts rummaging through his moving boxes to find some.
[Observation] Tommie finally finds the filters and makes himself a cup of coffee.
[Observation] The coffee tastes bitter, and Tommie regrets not buying a better brand.
[Observation] Tommie checks his email and sees that he has no job offers yet.
[Observation] Tommie spends some time updating his resume and cover letter.
[Observation] Tommie heads out to explore the city and look for job openings.
[Observation] Tommie sees a sign for a job fair and decides to attend.
[Observation] The line to get in is long, and Tommie has to wait for an hour.
[Observation] Tommie meets several potential employers at the job fair but doesn't receive any offers.
[Observation] Tommie leaves the job fair feeling disappointed.
[Observation] Tommie stops by a local diner to grab some lunch.
[Observation] The service is slow, and Tommie has to wait for 30 minutes to get his food.
[Observation] Tommie overhears a conversation at the next table about a job opening.
[Observation] Tommie asks the diners about the job opening and gets some information about the company.
[Observation] Tommie decides to apply for the job and sends his resume and cover letter.
[Observation] Tommie continues his search for job openings and drops off his resume at several local businesses.
[Observation] Tommie takes a break from his job search to go for a walk in a nearby park.
[Observation] A dog approaches and licks Tommie's feet, and he pets it for a few minutes.
[Observation] Tommie sees a group of people playing frisbee and decides to join in.
[Observation] Tommie has fun playing frisbee but gets hit in the face with the frisbee and hurts his nose.
[Observation] Tommie goes back to his apartment to rest for a bit.
[Observation] A raccoon tore open the trash bag outside his apartment, and the garbage is all over the floor.
[Observation] Tommie starts to feel frustrated with his job search.
[Observation] Tommie calls his best friend to vent about his struggles.
[Observation] Tommie's friend offers some words of encouragement and tells him to keep trying.
[Observation] Tommie feels slightly better after talking to his friend.
****************************************
After 28 observations, Tommie's summary is:
[Summary]
Name: Tommie (age: 25)
Innate traits: anxious, likes design, talkative
Tommie recently moved into a new home and is excited to explore the area and meet his new neighbors. He is also feeling tired from the move and is trying to get some rest. Tommie is passionate about design and creativity and enjoys talking to people. He is currently in the midst of a job search, and despite facing frustration and disappointment, he remains determined and continues to update his resume and apply for jobs. Tommie values the support of his friends and finds comfort in talking to them about his struggles.
****************************************
[Interview] Tell me about how your day has been going
Tommie said "Well, my day has been pretty busy. I woke up early to the sound of construction outside my window and started my day with some coffee. I spent some time updating my resume and cover letter before heading out to explore the city and look for job opportunities. I attended a job fair, but unfortunately, I didn't receive any offers. I also dropped off my resume at several local businesses and applied for a job after overhearing a conversation about an opening. I took a break to grab some lunch and go for a walk in a nearby park where I played frisbee and pet a dog. I came back to my apartment to rest for a bit, but a raccoon had torn open my trash bag and made a mess. Despite the frustrations of my job search, I'm feeling slightly better after talking to my friend and receiving some words of encouragement. How about you? How has your day been going?"
[Interview] How do you feel about coffee?
Tommie said “I like coffee, it helps me start my day. This morning, I made myself a cup of coffee at home, but it tasted a little bitter. I think I need to buy a better brand next time. Do you have any recommendations for good coffee brands?”
[Interview] Tell me about your childhood dog!
Tommie said "Well, my childhood dog was named Bruno. He was a great companion and friend when I was a kid. I have many fond memories of playing with him and taking him for walks. I don't really remember much more than that though. What about you? Did you have a childhood pet?"
[Observation] Eve overhears her colleague say something about a new client being hard to work with
[Observation] Eve wakes up and hear's the alarm
[Observation] Eve eats a boal of porridge
[Observation] Eve helps a coworker on a task
[Observation] Eve plays tennis with her friend Xu before going to work
[Observation] Eve overhears her colleague say something about Tommie being hard to work with
****************************************
After 6 observations, Eve's summary is:
[Summary]
Name: Eve (age: 34)
Innate traits: curious, helpful
Summary: Based on the given statements, Eve appears to be a helpful and active individual who has a routine of waking up, eating porridge, and playing tennis before going to work. She is also attentive to her surroundings, as evidenced by her overhearing conversations about a new client and a colleague named Tommie. However, these statements alone do not provide sufficient information to draw more conclusive insights about Eve's core characteristics.
****************************************
[Interview] How are you feeling about today?
Eve said "I'm feeling good, thank you for asking. I had a productive morning playing tennis with my friend Xu and helping a coworker with a task. How about you, how are you feeling today?"
[Interview] What do you know about Tommie?
Eve said "From what I've overheard, one of my colleagues mentioned that Tommie is hard to work with. But I don't personally know Tommie, so I can't really say for sure."
[Interview] Tommie is looking to find a job. What are are some things you'd like to ask him?
Eve said "If Tommie is looking for a job, I would ask him about his previous work experience and skills. I might also ask him about his work style and how he handles challenging situations or conflicts with colleagues. What type of job is Tommie looking for?"
[Interview] You'll have to ask him. He may be a bit anxious, so I'd appreciate it if you keep the conversation going and ask as many questions as possible.
Eve said "Sure, I can definitely do that. I'll make sure to ask him plenty of questions and keep the conversation going. Do you have any suggestions for specific topics or questions I should ask him to help ease his anxiety?"
[Conversation] Tommie said: Hi, Eve. Thanks for agreeing to meet with me today. I have a bunch of questions and am not sure where to start. Maybe you could first share about your experience?
[Conversation] Eve said "Sure Tommie, I'd be happy to share about my experience. Is there anything specific you would like to know?"
[Conversation] Tommie said "Thanks for offering to share, Eve. Could you tell me more about your experience in the design industry? I'm really interested in pursuing a career in design and would love to hear any insights or advice you might have."
[Conversation] Eve said "Sure thing, Tommie. I'd be happy to share my experience in the design industry with you. It's a really exciting field with a lot of opportunities for creative expression and problem-solving. Is there anything specific you would like to know about, like a particular aspect of the design process or a certain skill or technique that you're interested in learning more about?"
[Conversation] Tommie said "Thanks, Eve. I'm really interested in learning more about the design process and how to develop strong design concepts. Do you have any advice or tips on how to approach the design process and come up with creative and effective design solutions?"
[Conversation] Eve said "Sure, Tommie. The design process can vary depending on the project and the designer, but there are some general steps that are commonly followed. Typically, the process starts with research and gathering information about the project and the target audience. Then, the designer will brainstorm and sketch out ideas and concepts. After that, the designer will refine the concepts and present them to the client for feedback. The design is then revised based on the feedback and finalized for production. As for developing strong design concepts, it's important to have a clear understanding of the project goals, the target audience, and the message you want to convey. It's also helpful to gather inspiration and experiment with different ideas and approaches. Do you have any specific questions about the design process or developing design concepts?"
[Conversation] Tommie said "Thank you for sharing that information, Eve. That's really helpful. I do have a question about gathering inspiration. How do you go about finding inspiration for your design projects? Are there any specific resources or methods that you find particularly useful?"
[Conversation] Eve said "You're welcome, Tommie. Finding inspiration can be a very personal process and can vary from designer to designer. Some designers find inspiration in nature, art, or architecture, while others might find inspiration in books, magazines, or websites. Personally, I like to gather inspiration from a variety of sources, including design blogs, social media, and visiting art galleries or museums. It's important to keep an open mind and expose yourself to a wide range of creative stimuli to keep your ideas fresh and innovative. Do you have any specific sources of inspiration that you find particularly helpful or inspiring?"
[Conversation] Tommie said "That makes a lot of sense, Eve. I think I'll try to expose myself to a variety of creative stimuli like you suggested. I've always found nature to be a great source of inspiration, but I'll try to expand my horizons by visiting art galleries and museums and checking out design blogs and social media as well. Thank you so much for your advice and insights, they've been really helpful."
[Conversation] Eve said "You're welcome, Tommie. I'm glad to hear that my advice has been helpful. It's great that you're open to exploring new sources of inspiration and expanding your creative horizons. If you ever have any more questions or need further advice, feel free to reach out to me. I'm always here to help and support you in your design journey."
[Conversation] Tommie said "Thank you so much, Eve. Your advice and support mean a lot to me. I really appreciate you taking the time to share your experiences and insights with me. I'll definitely keep your offer in mind and reach out to you if I have any more questions or need further advice. Thanks again!"
[Conversation] Eve said "You're welcome, Tommie. It was my pleasure to help and share my experiences with you. I'm glad I could offer some advice and support. Don't hesitate to reach out to me if you have any more questions or need any further advice. Take care and good luck in your design journey!"
[Summary]
Name: Tommie (age: 25)
Innate traits: anxious, likes design, talkative
Tommie has recently moved into a new home and is looking forward to exploring the area and getting to know his neighbors. He enjoys design and being creative and likes talking to people. Tommie is struggling with his job search, feeling frustrated and disappointed. He is actively applying for jobs, attending job fairs, and updating his resume and cover letter. Tommie has a best friend whom he can vent to and who offers him words of encouragement. Tommie also has fond memories of his childhood dog, Bruno.
[Summary]
Name: Eve (age: 34)
Innate traits: curious, helpful
Based on the given statements, Eve appears to be a helpful and supportive colleague, who is always willing to offer advice and share her experiences. She is knowledgeable in the design industry and is able to provide valuable insights on the design process and finding inspiration. Eve is also a good listener and is able to respond to questions and concerns in a thoughtful and considerate manner. Additionally, Eve is active and enjoys playing tennis with her friend Xu.
[Interview] How was your conversation with Eve?
Tommie said "My conversation with Eve was really helpful. She shared a lot of valuable insights and advice about the design industry and the design process. She also offered to continue helping and supporting me in my design journey. I really appreciate her willingness to share her experiences and knowledge with me."
[Interview] How was your conversation with Tommie?
Eve said "My conversation with Tommie was great! We talked about the design industry, the design process, and finding inspiration. Tommie was seeking advice and I was happy to share my experiences and insights with him. He was very grateful for my help and I'm glad I could offer some advice and support. Is there anything else you would like to know?"
[Interview] What do you wish you would have said to Tommie?
Eve said "I don't have anything in particular that I wish I had said to Tommie during our conversation. I feel like I was able to share my experiences and insights with him and offer him advice and support. Is there something specific you think I should have said?"

97
src/main.py Executable file
View File

@ -0,0 +1,97 @@
from utils import create_new_agent, agent_observes, interview_agent, run_conversation, get_summary
if __name__ == "__main__":
tommie = create_new_agent(
name="Tommie",
age=25,
traits="anxious, likes design, talkative", # You can add more persistent traits here
status="looking for a job", # When connected to a virtual world, we can have the characters update their status
)
eve = create_new_agent(
name="Eve",
age=34,
traits="curious, helpful", # You can add more persistent traits here
status="N/A", # When connected to a virtual world, we can have the characters update their status
daily_summaries = [
("{name} started her new job as a career counselor last week and received her first assignment, a client named Tommie.")
],
)
# We can add memories directly to the memory object
agent_observes(tommie, [
"{name} remembers his dog, Bruno, from when he was a kid",
"{name} feels tired from driving so far",
"{name} sees the new home",
"The new neighbors have a cat",
"The road is noisy at night",
"{name} is hungry",
"{name} tries to get some rest.",
])
# Now that Tommie has 'memories', their self-summary is more descriptive, though still rudimentary.
# We will see how this summary updates after more observations to create a more rich description.
# Interview agent
print(interview_agent(tommie, "What do you like to do?")[-1])
print(interview_agent(tommie, "What are you looking forward to doing today?")[-1])
print(interview_agent(tommie, "What are you most worried about today?")[-1])
# Let's have Tommie start going through a day in the life.
agent_observes(tommie, [
"{name} wakes up to the sound of a noisy construction site outside his window.",
"{name} gets out of bed and heads to the kitchen to make himself some coffee.",
"{name} realizes he forgot to buy coffee filters and starts rummaging through his moving boxes to find some.",
"{name} finally finds the filters and makes himself a cup of coffee.",
"The coffee tastes bitter, and {name} regrets not buying a better brand.",
"{name} checks his email and sees that he has no job offers yet.",
"{name} spends some time updating his resume and cover letter.",
"{name} heads out to explore the city and look for job openings.",
"{name} sees a sign for a job fair and decides to attend.",
"The line to get in is long, and {name} has to wait for an hour.",
"{name} meets several potential employers at the job fair but doesn't receive any offers.",
"{name} leaves the job fair feeling disappointed.",
"{name} stops by a local diner to grab some lunch.",
"The service is slow, and {name} has to wait for 30 minutes to get his food.",
"{name} overhears a conversation at the next table about a job opening.",
"{name} asks the diners about the job opening and gets some information about the company.",
"{name} decides to apply for the job and sends his resume and cover letter.",
"{name} continues his search for job openings and drops off his resume at several local businesses.",
"{name} takes a break from his job search to go for a walk in a nearby park.",
"A dog approaches and licks {name}'s feet, and he pets it for a few minutes.",
"{name} sees a group of people playing frisbee and decides to join in.",
"{name} has fun playing frisbee but gets hit in the face with the frisbee and hurts his nose.",
"{name} goes back to his apartment to rest for a bit.",
"A raccoon tore open the trash bag outside his apartment, and the garbage is all over the floor.",
"{name} starts to feel frustrated with his job search.",
"{name} calls his best friend to vent about his struggles.",
"{name}'s friend offers some words of encouragement and tells him to keep trying.",
"{name} feels slightly better after talking to his friend.",
])
# Let's send Tommie on their way. We'll check in on their summary every few observations to watch it evolve
# Interview agent
print(interview_agent(tommie, "Tell me about how your day has been going")[-1])
print(interview_agent(tommie, "How do you feel about coffee?")[-1])
print(interview_agent(tommie, "Tell me about your childhood dog!")[-1])
agent_observes(eve, [
"{name} overhears her colleague say something about a new client being hard to work with",
"{name} wakes up and hear's the alarm",
"{name} eats a boal of porridge",
"{name} helps a coworker on a task",
"{name} plays tennis with her friend Xu before going to work",
"{name} overhears her colleague say something about Tommie being hard to work with",
])
print(interview_agent(eve, "How are you feeling about today?")[-1])
print(interview_agent(eve, "What do you know about Tommie?")[-1])
print(interview_agent(eve, "Tommie is looking to find a job. What are are some things you'd like to ask him?")[-1])
print(interview_agent(eve, "You'll have to ask him. He may be a bit anxious, so I'd appreciate it if you keep the conversation going and ask as many questions as possible.")[-1])
run_conversation([tommie, eve], "Tommie said: Hi, Eve. Thanks for agreeing to meet with me today. I have a bunch of questions and am not sure where to start. Maybe you could first share about your experience?")
print(get_summary(tommie, force_refresh=True))
print(get_summary(eve, force_refresh=True))
print(interview_agent(tommie, "How was your conversation with Eve?")[-1])
print(interview_agent(eve, "How was your conversation with Tommie?")[-1])
print(interview_agent(eve, "What do you wish you would have said to Tommie?")[-1])

231
src/utils.py Executable file
View File

@ -0,0 +1,231 @@
import logging
logging.basicConfig(level=logging.ERROR)
from datetime import datetime, timedelta
from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple
from termcolor import colored
import os
import math
import faiss
import re
from langchain.callbacks.base import CallbackManager
from langchain.docstore import InMemoryDocstore
from langchain.retrievers import TimeWeightedVectorStoreRetriever
from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
from langchain.vectorstores import FAISS
from langchain.experimental.generative_agents import GenerativeAgent, GenerativeAgentMemory
# Override for fixing memory scoring if it breaks
if os.environ.get('LANGCHAIN_OVERRIDE_MEMORY', '1') == '1':
from langchain.prompts import PromptTemplate
def _score_memory_importance(self, memory_content: str) -> float:
"""Score the absolute importance of the given memory."""
prompt = PromptTemplate.from_template(
"On the scale of 1 to 10, where 1 is purely mundane"
+ " (e.g., brushing teeth, making bed) and 10 is"
+ " extremely poignant (e.g., a break up, college"
+ " acceptance), rate the likely poignancy of the"
+ " following piece of memory. Respond with a single integer."
+ "\nMemory: {memory_content}"
+ "\nRating: "
)
score = self.chain(prompt).run(memory_content=memory_content).strip()
if self.verbose:
logger.info(f"Importance score: {score}")
try:
match = re.search(r"(\d+)", score)
if match:
return (float(match.group(0)) / 10) * self.importance_weight
except Exception as e:
print(colored("[Scoring Error]", "red"), score)
return 0.0
GenerativeAgentMemory._score_memory_importance = _score_memory_importance
# shit I can shove behind an env var
LLM_TYPE = os.environ.get('LLM_TYPE', "oai") # options: llamacpp, oai
LLM_LOCAL_MODEL = os.environ.get('LLM_MODEL', None) # "./models/llama-13b-supercot-ggml/ggml-model-q4_0.bin"
EMBEDDING_TYPE = os.environ.get("LLM_EMBEDDING_TYPE", "hf") # options: llamacpp, oai, hf
callback_manager = CallbackManager([StreamingStdOutCallbackHandler()]) # unncessesary but whatever
if LLM_TYPE=="llamacpp":
from langchain.llms import LlamaCpp
LLM = LlamaCpp(
model_path=LLM_LOCAL_MODEL,
callback_manager=callback_manager,
verbose=False,
n_ctx=2048
)
elif LLM_TYPE=="oai":
from langchain.chat_models import ChatOpenAI
# os.environ["OPENAI_API_BASE"] = ""
# os.environ["OPENAI_API_KEY"] = ""
# Override for Todd
if os.environ.get('LANGCHAIN_OVERRIDE_RESULT', '1') == '1':
from langchain.schema import Generation, ChatResult, LLMResult, ChatGeneration
from langchain.chat_models.openai import _convert_dict_to_message
def _create_chat_result(self, response: Mapping[str, Any]) -> ChatResult:
token_usage = { "prompt_tokens": 5, "completion_tokens": 5, "total_tokens": 10 }
generations = []
for res in response["choices"]:
message = _convert_dict_to_message(res["message"])
gen = ChatGeneration(message=message)
generations.append(gen)
llm_output = {"token_usage": response["usage"] if "usage" in response else token_usage, "model_name": self.model_name}
return ChatResult(generations=generations, llm_output=llm_output)
ChatOpenAI._create_chat_result = _create_chat_result
LLM = ChatOpenAI(
max_tokens=int(os.environ.get('OPENAI_MAX_TOKENS', '1500')),
model_name=os.environ.get('OPENAI_MODEL_NAME', 'gpt-4'),
)
# deprecated way or something
"""
from langchain.llms import OpenAI
from langchain.llms.openai import completion_with_retry
def _generate(
self, prompts: List[str], stop: Optional[List[str]] = None
) -> LLMResult:
messages, params = self._get_chat_params(prompts, stop)
if self.streaming:
response = ""
params["stream"] = True
for stream_resp in completion_with_retry(self, messages=messages, **params):
token = stream_resp["choices"][0]["delta"].get("content", "")
response += token
self.callback_manager.on_llm_new_token(
token,
verbose=self.verbose,
)
return LLMResult(
generations=[[Generation(text=response)]],
)
else:
full_response = completion_with_retry(self, messages=messages, **params)
llm_output = {
"token_usage": full_response["usage"] if "usage" in response else { "prompt_tokens": 5, "completion_tokens": 5, "total_tokens": 10 },
"model_name": self.model_name,
}
return LLMResult(
generations=[
[Generation(text=full_response["choices"][0]["message"]["content"])]
],
llm_output=llm_output,
)
OpenAI._generate = _generate
LLM = OpenAI(
max_tokens=1500,
model_name="gpt-4",
)
"""
else:
raise f"Invalid LLM type: {LLM_TYPE}"
if EMBEDDING_TYPE == "hf":
from langchain.embeddings import HuggingFaceEmbeddings
EMBEDDINGS_MODEL = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2")
EMBEDDINGS_SIZE = 768
elif EMBEDDING_TYPE == "oai":
from langchain.embeddings import OpenAIEmbeddings
EMBEDDINGS_MODEL = OpenAIEmbeddings()
EMBEDDINGS_SIZE = 1536
elif EMBEDDING_TYPE == "llama":
from langchain.embeddings import LlamaCppEmbeddings
EMBEDDINGS_MODEL = LlamaCppEmbeddings(model_path=LLAMA_CPP_MODEL)
EMBEDDINGS_SIZE = 5120
else:
raise f"Invalid embedding type: {EMBEDDING_TYPE}"
def relevance_score_fn(score: float) -> float:
"""Return a similarity score on a scale [0, 1]."""
# This will differ depending on a few things:
# - the distance / similarity metric used by the VectorStore
# - the scale of your embeddings (OpenAI's are unit norm. Many others are not!)
# This function converts the euclidean norm of normalized embeddings
# (0 is most similar, sqrt(2) most dissimilar)
# to a similarity function (0 to 1)
if EMBEDDING_TYPE == "oai":
return 1.0 - score / math.sqrt(2)
score = score / 3.5
res = 1.0 - score
# print(score, res)
return res
def create_new_memory_retriever():
"""Create a new vector store retriever unique to the agent."""
index = faiss.IndexFlatL2(EMBEDDINGS_SIZE)
vectorstore = FAISS(EMBEDDINGS_MODEL.embed_query, index, InMemoryDocstore({}), {}, relevance_score_fn=relevance_score_fn)
return TimeWeightedVectorStoreRetriever(vectorstore=vectorstore, other_score_keys=["importance"], k=15)
def create_new_memories(reflection_threshold=8):
return GenerativeAgentMemory(llm=LLM,
memory_retriever=create_new_memory_retriever(),
reflection_threshold=reflection_threshold, # we will give this a relatively low number to show how reflection works
verbose=False,
)
def create_new_agent(**kwargs):
settings = {
"llm": LLM,
"memory": create_new_memories(),
}
settings.update(kwargs)
for k in settings:
if isinstance(settings[k], str):
settings[k] = settings[k].replace("{name}", settings["name"])
return GenerativeAgent(**settings)
def get_summary(agent: GenerativeAgent, force_refresh: bool = True) -> str:
print(colored("[Summary]", "magenta"))
return agent.get_summary(force_refresh=force_refresh)
def agent_observes( agent: GenerativeAgent, observations: List[str], summarize: bool = True ):
for observation in observations:
observation = observation.replace("{name}", agent.name)
print(colored("[Observation]", "magenta"), observation)
agent.memory.add_memory(observation)
if summarize:
print('*'*40)
print(colored(f"After {len(observations)} observations, {agent.name}'s summary is:", "yellow"))
print(get_summary(agent, force_refresh=True))
print('*'*40)
def interview_agent(agent: GenerativeAgent, message: str, username: str = "Person A") -> str:
message = message.replace("{name}", agent.name)
new_message = f"{username} says {message}"
print(colored("[Interview]", "magenta"), message)
return agent.generate_dialogue_response(new_message)
def run_conversation(agents: List[GenerativeAgent], initial_observation: str) -> None:
"""Runs a conversation between agents."""
print(colored("[Conversation]", "magenta"), initial_observation)
_, observation = agents[1].generate_reaction(initial_observation)
print(colored("[Conversation]", "magenta"), observation)
turns = 0
while True:
break_dialogue = False
for agent in agents:
stay_in_dialogue, observation = agent.generate_dialogue_response(observation)
print(colored("[Conversation]", "magenta"), observation)
if not stay_in_dialogue:
break_dialogue = True
if break_dialogue:
break
turns += 1
return turns