<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Max Brodeur-Urbas on Medium]]></title>
        <description><![CDATA[Stories by Max Brodeur-Urbas on Medium]]></description>
        <link>https://medium.com/@max_82395?source=rss-43cf42fafd89------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*73Ios1i_8ssd_ztzoWrSSQ.jpeg</url>
            <title>Stories by Max Brodeur-Urbas on Medium</title>
            <link>https://medium.com/@max_82395?source=rss-43cf42fafd89------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 01:57:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@max_82395/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[AI Hallucinations and How to Avoid Them]]></title>
            <link>https://medium.com/@max_82395/ai-hallucinations-and-how-to-avoid-them-1ba9989525a4?source=rss-43cf42fafd89------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ba9989525a4</guid>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Max Brodeur-Urbas]]></dc:creator>
            <pubDate>Tue, 19 Dec 2023 22:11:21 GMT</pubDate>
            <atom:updated>2023-12-19T22:11:21.788Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NGljZUYkOfmpB-fYdn0stw.png" /><figcaption>GPT cooking up some nonsensical garbage output</figcaption></figure><p>AI hallucinations are one of the most frustrating and time consuming parts of building AI applications. Not only is the AI wrong but it’s convincing which makes things much trickier. Here are some tips on how to reliably avoid hallucinations.</p><h3>What is an AI Hallucination</h3><p>This might be obvious but a hallucination is the AI (LLMs specifically) making s*$% up. It is responding to your questions with nonsense and doing so with confidence. This convincingness is the real source of the issue. If there was an easy way to spot hallucinations you could solve the problem by catching and handling errors like any other software system. <strong>The only effective way to deal with hallucinations is prevention.</strong></p><h3>Why does AI Hallucinate</h3><p>I like to imagine AI (LLMs) as a rock climber and you (the engineer) as its belayer. You’re responsible for setting the holds/mapping out a route based on the model’s skill level, guiding it verbally through the tricky sections and giving it a cheeky pull up the wall when you expect it to struggle. Hallucinations are a result of expecting too much from the AI at a given move in the climb. <strong>It will do anything to please you, even if that means cheating a little bit.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XzRVYWrw6XOkF5IV" /><figcaption><em>How I envision GPT in this climbing analogy</em></figcaption></figure><h3>Hallucinations = Skill Issue</h3><p>Hallucinations are caused by one of two skill issues. Either the model isn’t capable enough to complete the task or you didn’t guide it effectively. Failing to guide it can take many shapes but is generally related to context as that’s all you really have control over. It’s possible you overloaded it with context, didn’t give it enough context or didn’t give it the correct context among other things. People are quick to blame the model for hallucinating but don’t evaluate their approach critically enough.</p><p>Here are 4 techniques I use that help ensure the AI never feels the need to cheat and make things up.</p><h3>Reduce the Problem Space</h3><p>Wherever possible, simplify the problem being given to the AI. Put those rock climbing holds as close together as possible so that it’s almost impossible to fail. Breaking one difficult move up into 4 smaller moves makes things much more reliable. This may mean making more AI calls and some the system being slower overall but for most business use cases, being reliable and correct is all that matters.</p><p>If you have a task where you’d like the AI to extract 3 pieces of data from a source and generate analysis, break it up into 4 much smaller steps. Extract each piece of data independently in parallel, concatenate the results and pass that into the final analysis step. This is one of many many ways we can simplify a problem like this but as long as you’re breaking things up into simpler steps, you’re heading in the right direction.</p><p>If you simplify your tasks enough, you’ll find they’ve become so trivial that the much less capable models are now viable solutions. In the example above, you may have needed 3 extra calls but if the model you’re now able to use is 20x less expensive, you’re reducing costs while increasing reliability!</p><h3>Context Saturated Prompting</h3><p>It is your job to ensure there is no room for confusion from the models perspective. In our climbing analogy, this is you yelling hyper specific instructions up the wall while sitting back a bit in your harness to pull the model through the move. When I say provide the correct context, I don’t mean simply giving it a bit of background info. I mean absolutely saturating your prompt in the most relevant information possible using relevant examples, explaining common pitfalls, clarifying key terms, dynamically injecting relevant chunks, explaining failure scenarios etc.</p><p>This part of the process is where the real engineering comes in. This is the ‘prompt’ engineering people say they’re doing but I think it would be better labeled as ‘context’ engineering. It’s essential to not cut corners here because providing insufficient context is the perfect opportunity for the AI to fill in the blanks with wildly reasonable hallucinations.</p><h3>Add Validation Steps</h3><p>This part is difficult since hallucinations are inherently convincing but coming up with basic sanity checks can go a long way. This is also extremely dependent on the task at hand but there’s always some imaginative way you should be able to ensure some non-zero confidence in the answer.</p><ul><li>if it’s data extraction, validate the data and perform a keyword search on the source to confirm it was present.</li><li>If it’s content generation, use a cheaper model to sanity check the structure.</li><li>If it’s quoting sources, scrape the source for the relevant quote.</li><li>If you’re expecting JSON responses, load the JSON and confirm it matches a set of schema.</li></ul><p>These sorts of steps near the end of your process give you the opportunity to use a fail safe you may have built. Regardless of what your backup plan is, it’s better you were warned than the hallucination quietly slipping by you.</p><h3>Use as Little AI as Possible</h3><p>Your ultimate goal is to get the climber to the top of the wall. If you can let them take a break and just pull them past certain sections, take that opportunity. The less AI you use, the less chance there is for hallucinations and the cheaper things get! Oftentimes people try to use AI for absolutely every part of their process but don’t consider that a simple python script or API call could have done most of the job. The less you use AI the cheaper your solution will get and the more budget you’ll have on the sections that can’t be solved without AI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HP9jrHxozLfqyae1" /><figcaption><em>Your AI celebrating at the top after hallucinating its way there</em></figcaption></figure><p>Within AgentHub, our typical automations are ~10% AI and 90% infrastructure. That infrastructure is loading data from third parties, taking user input and formatting data in preparation for the expensive AI steps. We specialize in helping you define these rigid workflows (climbing routes) for your AI to reliably accomplish. If you have a task that you’ve been hoping to have AI take over, we have can help you automate it.</p><p>The only perfect way to avoid hallucinations is to avoid using AI altogether. The best contraception is abstinence as they say (I don’t). If you are using AI however, practice safe development and hopefully these tips help.</p><p>Feel free to check out <a href="https://www.agenthub.dev/">AgentHub</a> and start automating work with no code!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ba9989525a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Label Data with Generative AI]]></title>
            <link>https://medium.com/@max_82395/how-to-label-data-with-generative-ai-e40050f8481c?source=rss-43cf42fafd89------2</link>
            <guid isPermaLink="false">https://medium.com/p/e40050f8481c</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Max Brodeur-Urbas]]></dc:creator>
            <pubDate>Tue, 19 Dec 2023 22:01:03 GMT</pubDate>
            <atom:updated>2023-12-19T22:01:03.670Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*DtNO9H5xb736khUIfJ8BKQ.png" /><figcaption>You hyper intelligent data labeller hard at work.</figcaption></figure><p>Before LLMs, you needed some level of machine learning experience and heaps of data in order to deploy any custom data labeling pipeline. Now you can achieve similar results with a carefully worded prompt.</p><h3>Why Label Data with AI</h3><p>Labeling is one of the most common things people try to use AI for when processing their data. Common use cases I see are people labeling…</p><ul><li>product reviews as positive or negative</li><li>GitHub issues into categories</li><li>essays with a letter grade</li><li>sales leads into their respective industries</li><li>emails into folders</li><li>research papers into fields of study</li></ul><p>Generally, when someone is hoping to create a data labeling pipeline they’re trying to process data at scale. It should take them less time to build the solution then it would to manually go through the data. Thankfully, setting up a powerful data labeling pipeline only takes a few minutes with the help of generative AI.</p><p>Here are some general tips to leverage AI (GPT specifically) to categorize large amounts of data in a cost-effective and reliable way.</p><h3>Functions</h3><p>When categorizing with large language models, you might encounter the frustration of receiving more than just the answer. If you’re using GPT and aren’t using Functions/JSON mode yet you’re missing out. I wrote <a href="https://www.agenthub.dev/blog/gpt_functions_guide">more about functions here</a> but they are the absolute best way to ensure GPT is returning nothing but the label/category as output.</p><p>Without functions, you may get a reply like “Sure, I’ve decided to categorize this object as…” which would most likely throw a wrench in your data processing pipeline.</p><h3>Include a Justification</h3><p>Understanding why the label was selected is super helpful for debugging or justifying decisions. One trick we often use is requesting a short justification for why the decision was made. This is especially useful during the initial iterations of the pipeline because it surfaces any incorrect assumptions and blind spots in the LLMs understanding of the task</p><p>We normally request a justification as part of the same function definition. Here’s an example of a GPT function we used to categorize news stories.</p><pre>{<br>  &quot;name&quot;: &quot;categorize&quot;,<br>  &quot;description&quot;: &quot;Categorize the input data into user defined buckets.&quot;,<br>  &quot;parameters&quot;: {<br>    &quot;type&quot;: &quot;object&quot;,<br>    &quot;properties&quot;: {<br>      &quot;category&quot;: {<br>        &quot;type&quot;: &quot;string&quot;,<br>        &quot;enum&quot;: [&quot;US Politics&quot;, &quot;Pandemic&quot;, &quot;Economy&quot;, &quot;Pop culture&quot;, &quot;Other&quot;],<br>        &quot;description&quot;: &quot;US Politics: Related to US politics or US politicians, Pandemic: Related to the Coronavirus Pandemix, Economy: Related to the economy of a specific country or the world. , Pop culture: Related to pop culture, celebrity media or entertainment., Other: Doesn&#39;t fit in any of the defined categories. &quot;<br>      },<br>      &quot;justification&quot;: {<br>        &quot;type&quot;: &quot;string&quot;,<br>        &quot;description&quot;: &quot;A short justification explaining why the input data was categorized into the selected category.&quot;<br>      }<br>    },<br>    &quot;required&quot;: [&quot;category&quot;, &quot;justification&quot;]<br>  }<br>}</pre><h3>Failure Labels</h3><p>It’s essential to always have a failure category/label so the ai model can declare it’s confused if needed. Without a failure category like ‘other’ or ‘unknown’ the model will try to force an ill fitting category much more often.</p><p>A false positive is a worst case scenario because it increases the doubt in all of your models’ responses. I tend to be hyper cautious in my prompt and request the model default to this failure category if it has any uncertainty whatsoever.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*83ntMbfhMD7NFHvW" /><figcaption><em>AI self reporting it failed</em></figcaption></figure><h3>Escalate Failures</h3><p>There are multiple approaches you can take to handle these failure scenarios. The most reliable is to escalate directly to human intervention but this is often not scalable for large scale tasks. A similarly reliable approach is to waterfall your labeling requests by escalating it to a more capable (and often more expensive) ai model.</p><p>You can use some base level LLM like GPT-3.5 to handle the brunt of the work while prompting it to always default to this failure category when unsure. You can then feed all data labeled “Other” to increasingly more capable models with more provided context.</p><p>This waterfall approach should help address the large majority of edge cases in a cost effective, scalable and reliable way.</p><h3>Sub-Categories</h3><p>Defining too many categories in a single prompt will negatively impact results. As a general rule, the larger your prompt, the more likely your LLM is to get confused and fail to follow instructions. GPT functions are no exception to this rule, a very long function definition will cause hallucinations or errors. One strategy we’ve used in sub-categorization to get more refined results.</p><p>If you’re labeling github tasks for example, defining an initial labeling of frontend/backend followed by two separate sets of more granular options should help reduce your prompt size by 50%.</p><h3>Data Labeling on AgentHub</h3><p>AgentHub is a platform that allows you to build complex AI-powered automations with no code. One thing we pride ourselves on is the simplification of common tasks like scaled data labeling. We have a prebuilt ‘Categorizer’ node that allows you to even more easily get up and running with only a few sentences.</p><p>Happy labeling!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e40050f8481c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Everything to know for your Y Combinator interview]]></title>
            <link>https://medium.com/@max_82395/everything-to-know-for-your-y-combinator-interview-23f9aff809f2?source=rss-43cf42fafd89------2</link>
            <guid isPermaLink="false">https://medium.com/p/23f9aff809f2</guid>
            <category><![CDATA[silicon-valley]]></category>
            <category><![CDATA[ycombinator]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[entrepreneurship]]></category>
            <category><![CDATA[startup]]></category>
            <dc:creator><![CDATA[Max Brodeur-Urbas]]></dc:creator>
            <pubDate>Tue, 19 Dec 2023 21:54:27 GMT</pubDate>
            <atom:updated>2023-12-20T19:48:35.685Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4mzH2_8YqowzxB6FH0eMAw.png" /></figure><p>I’ve interviewed with YC 4 times. 3 rejections and 1 acceptance. I’m asked a few times a week how to best prepare for an interview so I thought I’d package the most important points into a single blog post.</p><p>If you’re reading this you are probably expecting an interview or have one coming up. Exciting!</p><h3>What to expect</h3><p>The interview is 10 minutes. You’ll join a zoom waiting room 15 minutes before your interview time. They’ve always been a few minutes late in my experience (they’re conducting hundreds of interviews that day, can’t blame them).</p><p>Once you’re let in, you’ll most likely be staring back at 3+ interviewers. The most unique aspect of the interview is that there are no pleasantries, no introductions or small talk. They start off with their questions immediately.</p><p>One main interviewer will lead the call and start asking questions. Other interviewers will chime in more as the call progresses. The 10 quickest minutes of your year will fly by. They’ll thank you and hang up. That’s it.</p><h3>When to expect an answer</h3><p>This is the worst part. Waiting for an answer can feel like an eternity. An email or phone call within the next 24 hours is standard. An email if you didn’t get in or a phone call from your interviewing partner if you did.</p><p>Googling “what time does YC send out answers after interviewing” will return tons of forum posts from stressed out applicants. If you find yourself googling that, or ended up here because of that search, try and do something else. It’s completely random. In my cases:</p><ul><li><strong>Interview 1: Rejection email at 11:30 PM PST</strong></li><li><strong>Interview 2: Rejection email at 9:21 PM PST</strong></li><li><strong>Interview 3: Rejection email the next morning at 8:55 AM PST</strong></li><li><strong>Interview 4: Phone call at 8:55 PM PST</strong></li></ul><p>In my experience, their rejection emails are extremely thoughtful and full of actionable advice. It is normally a long email detailing exactly why they are passing on your application and what they’d want to see in the future. Even though it’s disappointing to read at the time, this email makes the entire stressful interview process worth it.</p><p>If you get accepted, the phone call comes from the primary interviewer. They are the person who decided to admit you. There is no consensus necessary between interviewers, all you need is one partner to give you the go-ahead.</p><h3>My 5 pieces of advice.</h3><blockquote>“Advice is a form of nostalgia. Dispensing it is a way of fishing the past from the disposal, wiping it off, painting over the ugly parts and recycling it for more than it’s worth.” — Mary Schmich</blockquote><p>This advice is based on my personal experience and is jam packed with assumptions. Take what I say with a grain of salt!</p><h3>1. Get the first question right.</h3><blockquote>“What are you working on?”</blockquote><p>This will be the first question almost every time. This is a very genuine question from your interviewer as they probably don’t know. Even though you packed all the info into your application it’s unlikely they had more than a few minutes to read through it before hopping on the call.</p><p>Your answer here lays the foundation for the rest of the interview. Their intention is to explore every aspect of your startup with you, but if they don’t know what the startup does it’s impossible to have a fruitful conversation. If they need to use the extremely limited interview time to have you elaborate your answer here you’re losing out on a chance to truly discuss the startup.</p><p>Your goal is to paint a very clear and simple mental image for your interviewer. Give them that ‘ah, got it’ moment they’re hoping for with a clear and concise answer. The single best tip I can give here is to anchor your answer to a concept they’re familiar with.</p><blockquote>“AgentHub is a no-code platform to automate complex workflows with AI. It’s like Zapier, but if they are a simple calculator, we would be Wolfram Alpha”</blockquote><p>We start with a one liner about our product and follow up with a comparison to a product they’re undoubtedly familiar with (Zapier is a YC company) to give them an immediate reference point.</p><p>Using this approach of “Like X for Y” or “Like X, but with Y” is the thing that set my successful interview apart from my previous ones. I highly recommend it.</p><h3>2. Practice makes possible</h3><p>The interview is short and (can be) intense. You can’t afford to waste time deciding which co-founder will answer or thinking about anything for the first time. <strong>Other than building your product</strong>, running through practice interviews is the best thing you can do to prepare.</p><p>I’d recommend finding a handful of friends who are willing to hop on a 15 minute call, grill you for 10 and tell you why they doubt you’ll succeed for 5. The goal here is not to have rehearsed answers, but to feel comfortable answering any and all questions.</p><p>I’ve found that when I’m really confident in an idea, I am not only happy to answer any question about it, but literally excited to address it. Practicing helps make you more confident in this way and helps pinpoint the questions you are uncomfortable answering.</p><h3>3. Focus on what makes you uncomfortable</h3><p>The YC partners are not joining a call to talk about how great you are or how much they love the concept. They have 10 minutes to really get to the bottom of things. In my experience they tend to focus on the weakest part of your startup. Focus on these uncomfortable questions while you prepare. I think this is a great exercise for evaluating your startup in general, but especially important because you will be asked these + followups in the interview.</p><p>The important part here is not that you have a perfect answer for everything, but that you’re able to show you’ve thoroughly thought through every aspect of the startup. Being able to inspect your own ideas through a critical lens is an important skill.</p><p>Many parts of the initial AgentHub strategy on interview day were bad in hindsight. These very ideas were the ones the partners challenged us on. Even though we weren’t right, we had really thought through the problem and came up with an informed hypothesis we were eager to test/disprove.</p><h3>4. Prove you will succeed regardless</h3><p>The company YC is most eager to admit is the one that needs YC the least (completely unfounded opinion :) ). If you’re able to prove in the interview that you will succeed without YC, you’re a perfect fit.</p><p>My co-founder Rahul and I were chatting about this recently. We would see a flurry of twitter posts from YC-affiliated founders encouraging everyone to apply to before the deadline. We were both thinking, ‘why would they need to advertise this?’</p><p>We realized these posts are aimed at the people who don’t want to do YC. These are the founders who know they’re going to succeed regardless and are already taking steps towards success. This founder will go far independently, but with YC’s help, they can go even further and faster.</p><h3>5. Try to have fun</h3><p>This point sounds cliche, but I think it’s important to add. Your interviewers want to see if they can work with you. Having their one interaction with you be a rigid/uncomfortable conversation is not memorable or enjoyable.</p><p>This is somewhat tied to practicing and being confident, but approaching the interview with excitement is important. <strong>It’s hard to get someone excited about your vision if even you don’t look excited to talk about it</strong>.</p><h3>Good luck</h3><p>I’ve spoken throughout this post as if I know exactly what YC wants. <em>I do not</em> . I’ve failed the YC interview 75% of the time but this is what I would have told you if you messaged me for advice!</p><p>Feel free to email me at max@agenthub.dev if you need help. Take a deep breath and build something awesome.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23f9aff809f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GPT Function Calling: 5 Underrated Use Cases]]></title>
            <link>https://medium.com/better-programming/gpt-function-calling-5-underrated-use-cases-ccbd1d3f9fd7?source=rss-43cf42fafd89------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccbd1d3f9fd7</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Max Brodeur-Urbas]]></dc:creator>
            <pubDate>Sun, 05 Nov 2023 02:08:38 GMT</pubDate>
            <atom:updated>2023-11-20T20:55:28.826Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*doghMb44J43LgPYtkUCByw.jpeg" /><figcaption>OpenAI’s backend converting messy unstructured data to structured data via functions</figcaption></figure><p>OpenAI’s “Function Calling” might be the most groundbreaking yet under appreciated feature released by any software company… ever.</p><h3>What are GPT Functions</h3><p>Functions allow you to <strong>turn unstructured data into structured data</strong>. This might not sound all that groundbreaking but when you consider that 90% of data processing and data entry jobs worldwide exist for this exact reason, it’s quite a revolutionary feature that went somewhat unnoticed.</p><p>Have you ever found yourself <em>begging</em> GPT (3.5 or 4) to spit out the answer you want and absolutely nothing else? No “Sure, here is your…” or any other useless fluff surrounding the core answer. GPT Functions are the solution you’ve been looking for.</p><h4>How are Functions meant to work?</h4><blockquote>OpenAI’s docs on function calling are extremely limited. You’ll find yourself digging through their developer forum for examples of how to use them. I dug around the forum for you and have many example coming up.</blockquote><p>Here’s one of the only examples you’ll be able to find in their docs:</p><pre>functions = [<br>        {<br>            &quot;name&quot;: &quot;get_current_weather&quot;,<br>            &quot;description&quot;: &quot;Get the current weather in a given location&quot;,<br>            &quot;parameters&quot;: {<br>                &quot;type&quot;: &quot;object&quot;,<br>                &quot;properties&quot;: {<br>                    &quot;location&quot;: {<br>                        &quot;type&quot;: &quot;string&quot;,<br>                        &quot;description&quot;: &quot;The city and state, e.g. San Francisco, CA&quot;,<br>                    },<br>                    &quot;unit&quot;: {&quot;type&quot;: &quot;string&quot;, &quot;enum&quot;: [&quot;celsius&quot;, &quot;fahrenheit&quot;]},<br>                },<br>                &quot;required&quot;: [&quot;location&quot;],<br>            },<br>        }<br>    ]</pre><p>A function definition is a rigid JSON format that defines a function name, description and parameters. In this case, the function is meant to get the current weather. Obviously GPT isn’t able to call this actual API (since it doesn’t exist) but using this structured response you’d be able to connect the real API hypothetically.</p><p>At a high level however, functions provide two layers of inference:</p><h4>Picking the function itself:</h4><p>You may notice that functions are passed into the OpenAI API call as an array. The reason you provide a name and description to each function are so GPT can decide which to use based on a given prompt. Providing multiple functions in your API call is like giving GPT a Swiss army knife and asking it to cut a piece of wood in half. It knows that even though it has a pair of pliers, scissors and a knife, it should use the saw!</p><p><strong>Function definitions contribute towards your token count</strong>. Passing in hundreds of functions would not only take up the majority of your token limit but also result in a drop in response quality. I often don’t even use this feature and only pass in 1 function that I force it to use. It is very nice to have in certain use cases however.</p><h4>Picking the parameter values based on a prompt:</h4><p>This is the real magic in my opinion. GPT being able to choose the tool in it’s tool kit is amazing and definitely the focus of their feature announcement but I think this applies to more use cases.</p><p><strong>You can imagine a function like handing GPT a form to fill out</strong>. <strong>It uses its reasoning, the context of the situation and field names/descriptions to decide how it will fill out each field.</strong> Designing the form and the additional information you pass in is where you can get creative.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*YZEdqYdzo_LyCSK2YzQDrQ.png" /><figcaption>GPT filling out your custom form (function parameters)</figcaption></figure><h3>5 Useful Applications</h3><h3>Data Extraction</h3><p>One of the most common things I use functions for to extract specific values from a large chunk of text. The sender’s address from an email, a founders name from a blog post, a phone number from a landing page.</p><p>I like to imagine I’m searching for a needle in a haystack except the LLM burns the haystack, leaving nothing but the needle(s).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*nycFdIgLvj_RVyQ_J28r9A.png" /><figcaption>GPT Data Extraction Personified.</figcaption></figure><h4>Use case: Processing thousands of contest submissions</h4><p>I built an automation that iterated over thousands of contest submissions. Before storing these in a Google sheet I wanted to extract the email associated with the submission. Heres the function call I used for extracting their email.</p><pre>{<br>   &quot;name&quot;:&quot;update_email&quot;,<br>   &quot;description&quot;:&quot;Updates email based on the content of their submission.&quot;,<br>   &quot;parameters&quot;:{<br>      &quot;type&quot;:&quot;object&quot;,<br>      &quot;properties&quot;:{<br>         &quot;email&quot;:{<br>            &quot;type&quot;:&quot;string&quot;,<br>            &quot;description&quot;:&quot;The email provided in the submission&quot;<br>         }<br>      },<br>      &quot;required&quot;:[<br>         &quot;email&quot;<br>      ]<br>   }<br>}</pre><h3>Scoring</h3><p>Assigning unstructured data a score based on dynamic, natural language criteria is a wonderful use case for functions. You could score comments during sentiment analysis, essays based on a custom grading rubric, a loan application for risk based on key factors. A recent use case I applied scoring to was scoring of sales leads from 0–100 based on their viability.</p><h4>Use Case: Scoring Sales leads</h4><p>We had hundreds of prospective leads in a single google sheet a few months ago that we wanted to tackle from most to least important. Each lead contained info like company size, contact name, position, industry etc.</p><p>Using the following function we scored each lead from 0–100 based on our needs and then sorted them from best to worst.</p><pre>{<br>   &quot;name&quot;:&quot;update_sales_lead_value_score&quot;,<br>   &quot;description&quot;:&quot;Updates the score of a sales lead and provides a justification&quot;,<br>   &quot;parameters&quot;:{<br>      &quot;type&quot;:&quot;object&quot;,<br>      &quot;properties&quot;:{<br>         &quot;sales_lead_value_score&quot;:{<br>            &quot;type&quot;:&quot;number&quot;,<br>            &quot;description&quot;:&quot;An integer value ranging from 0 to 100 that represents the quality of a sales lead based on these criteria. 100 is a perfect lead, 0 is terrible. Ideal Lead Criteria:\n- Medium sized companies (300-500 employees is the best range)\n- Companies in primary resource heavy industries are best, ex. manufacturing, agriculture, etc. (this is the most important criteria)\n- The higher up the contact position, the better. VP or Executive level is preferred.&quot;<br>         },<br>         &quot;score_justification&quot;:{<br>            &quot;type&quot;:&quot;string&quot;,<br>            &quot;description&quot;:&quot;A clear and conscise justification for the score provided based on the custom criteria&quot;<br>         }<br>      }<br>   },<br>   &quot;required&quot;:[<br>      &quot;sales_lead_value_score&quot;, <br>      &quot;score_justification&quot;<br>   ]<br>}</pre><h3>Categorization:</h3><p>Define custom buckets and have GPT thoughtfully consider each piece of data you give it and place it in the correct bucket. This can be used for labelling tasks like selecting the category of youtube videos or for discrete scoring tasks like assigning letter grades to homework assignments.</p><h4><strong>Use Case: Labelling news articles.</strong></h4><p>A very common first step in data processing workflows is separating incoming data into different streams. A recent automation I built did exactly this with news articles scraped from the web. I wanted to sort them based on the topic of the article and include a justification for the decision once again. Here’s the function I used:</p><pre>{<br>   &quot;name&quot;:&quot;categorize&quot;,<br>   &quot;description&quot;:&quot;Categorize the input data into user defined buckets.&quot;,<br>   &quot;parameters&quot;:{<br>      &quot;type&quot;:&quot;object&quot;,<br>      &quot;properties&quot;:{<br>         &quot;category&quot;:{<br>            &quot;type&quot;:&quot;string&quot;,<br>            &quot;enum&quot;:[<br>               &quot;US Politics&quot;,<br>               &quot;Pandemic&quot;,<br>               &quot;Economy&quot;,<br>               &quot;Pop culture&quot;,<br>               &quot;Other&quot;<br>            ],<br>            &quot;description&quot;:&quot;US Politics: Related to US politics or US politicians, Pandemic: Related to the Coronavirus Pandemix, Economy: Related to the economy of a specific country or the world. , Pop culture: Related to pop culture, celebrity media or entertainment., Other: Doesn&#39;t fit in any of the defined categories. &quot;<br>         },<br>         &quot;justification&quot;:{<br>            &quot;type&quot;:&quot;string&quot;,<br>            &quot;description&quot;:&quot;A short justification explaining why the input data was categorized into the selected category.&quot;<br>         }<br>      },<br>      &quot;required&quot;:[<br>         &quot;category&quot;,<br>         &quot;justification&quot;<br>      ]<br>   }<br>}</pre><h3>Option-Selection:</h3><p>Often times when processing data, I give GPT many possible options and want it to select the best one based on my needs. I only want the value it selected, no surrounding fluff or additional thoughts. Functions are perfect for this.</p><h4>Use Case: Finding the “most interesting AI news story” from hacker news</h4><blockquote>I wrote another <a href="https://medium.com/better-programming/building-an-autonomous-twitter-account-with-llms-de53f5e519ba">medium article here</a> about how I automated my entire Twitter account with GPT. Part of that process involves selecting the most relevant posts from the front pages of hacker news. This post selection step leverages functions!</blockquote><p>To summarize the functions portion of the use case, we would scrape the first n pages of hacker news and ask GPT to select the post most relevant to “AI news or tech news”. GPT would return only the headline and the link selected via functions so that I could go on to scrape that website and generate a tweet from it.</p><p>I would pass in the user defined query as part of the message and use the following function definition:</p><pre>{<br>   &quot;name&quot;:&quot;find_best_post&quot;,<br>   &quot;description&quot;:&quot;Determine the best post that most closely reflects the query.&quot;,<br>   &quot;parameters&quot;:{<br>      &quot;type&quot;:&quot;object&quot;,<br>      &quot;properties&quot;:{<br>         &quot;best_post_title&quot;:{<br>            &quot;type&quot;:&quot;string&quot;,<br>            &quot;description&quot;:&quot;The title of the post that most closely reflects the query, stated exactly as it appears in the list of titles.&quot;<br>         }<br>      },<br>      &quot;required&quot;:[<br>         &quot;best_post_title&quot;<br>      ]<br>   }<br>}</pre><h3>Filtering:</h3><p>Filtering is a subset of categorization where you categorize items as either true or false based on a natural language condition. A condition like “is Spanish” will be able to filter out all Spanish comments, articles etc. using a simple function and conditional statement immediately after.</p><h4>Use Case: Filtering contest submission</h4><p>The same automation that I mentioned in the “Data Extraction” section used ai-powered-filtering to weed out contest submissions that didn’t meet the deal-breaking criteria. Things like “must use typescript” were absolutely mandatory for the coding contest at hand. We used functions to filter out submissions and trim down the total set being processed by 90%. Here is the function definition we used.</p><pre>{<br>   &quot;name&quot;:&quot;apply_condition&quot;,<br>   &quot;description&quot;:&quot;Used to decide whether the input meets the user provided condition.&quot;,<br>   &quot;parameters&quot;:{<br>      &quot;type&quot;:&quot;object&quot;,<br>      &quot;properties&quot;:{<br>         &quot;decision&quot;:{<br>            &quot;type&quot;:&quot;string&quot;,<br>            &quot;enum&quot;:[<br>               &quot;True&quot;,<br>               &quot;False&quot;<br>            ],<br>            &quot;description&quot;:&quot;True if the input meets this condition &#39;Does submission meet the ALL these requirements (uses typescript, uses tailwindcss, functional demo)&#39;, False otherwise.&quot;<br>         }<br>      },<br>      &quot;required&quot;:[<br>         &quot;decision&quot;<br>      ]<br>   }<br>}</pre><p>If you’re curious why I love functions so much or what I’ve built with them you should check out <a href="https://www.agenthub.dev/">AgentHub</a>!</p><p><strong>AgentHub is the </strong><a href="https://www.ycombinator.com/launches/JcG-agenthub-automate-any-workflow-with-ai"><strong>Y Combinator-backed startup</strong></a><strong> I co-founded that let’s you automate any repetitive or complex workflow with AI via a simple drag and drop no-code platform.</strong></p><blockquote>“Imagine Zapier but AI-first and on crack.” — Me</blockquote><p>Automations are built with individual nodes called “Operators” that are linked together to create power AI pipelines. We have a catalogue of AI powered operators that leverage functions under the hood.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U3Cqe59WNC6mFQn3-3O26A.png" /><figcaption>Our current AI-powered operators that use functions!</figcaption></figure><p>Check out these templates to see examples of function use-cases on AgentHub: <a href="https://www.agenthub.dev/templates/sales_crm/sales_leads_scoring_model">Scoring</a>, <a href="https://www.agenthub.dev/templates/media_news/news_story_categorizer">Categorization</a>, <a href="https://www.agenthub.dev/templates/media_news/autonomous_twitter_bot">Option-Selection</a>,</p><p>If you want to start building <a href="https://www.agenthub.dev/">AgentHub</a> is live and ready to use! We’re very active in our <a href="https://discord.gg/SyCVmrzhCc">discord community</a> and are happy to help you build your automations if needed.</p><p>Feel free to follow the <a href="https://twitter.com/AgentHub_AI">official AgentHub twitter</a> for updates and <a href="https://twitter.com/MaxBrodeurUrbas">myself for AI-related content.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccbd1d3f9fd7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/gpt-function-calling-5-underrated-use-cases-ccbd1d3f9fd7">GPT Function Calling: 5 Underrated Use Cases</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a GitHub Documentation Bot With LLMs]]></title>
            <link>https://medium.com/better-programming/automating-open-source-documentation-with-gpt4-5b6405881b1b?source=rss-43cf42fafd89------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b6405881b1b</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Max Brodeur-Urbas]]></dc:creator>
            <pubDate>Mon, 19 Jun 2023 20:34:10 GMT</pubDate>
            <atom:updated>2023-08-18T20:35:10.478Z</atom:updated>
            <content:encoded><![CDATA[<h4>All the documentation in my repo is generated by GPT4 and I can update these docs with the click of a button.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vFKG4j7eIxOwZrpAoMQ8mw.png" /><figcaption>The visual representation of my doc-bot hard at work.</figcaption></figure><p>The automation is powered by <a href="https://www.agenthub.dev/">AgentHub</a> and is able to read my GitHub project, generate new markdown docs, and publish the PR for me. Here’s how I made it and how you could build your own.</p><p>Why?</p><p>Trying to keep documentation up to date is like building a sandcastle below the tide line. You can work on perfecting it all you want but the tide of contributions is going to eventually roll in and turn it into meaningless mush. This is especially true in open-source projects with active communities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uDt3_kSXVy3nT_atwT3b7Q.png" /><figcaption><strong>“the remnants of a sandcastle after being washed away by the tide” by Midjourney </strong>🎨</figcaption></figure><blockquote>The essence of this art lies not in its longevity, but in its fleeting existence, reminding us that just like a sunset, true beauty often resides in the impermanent. — ChatGPT</blockquote><p>Let’s ignore the beauty of ephemeral art in this analogy and acknowledge that <em>re-writing documentation is a pain</em>. It can be so frustrating that many projects ignore it, letting their documentation degrade to the point of needing a complete rewrite. Even if they do allocate time for it, an engineer who knows enough to write the docs shouldn’t be spending their valuable time writing them.</p><p>I built an LLM-powered pipeline on <a href="https://www.agenthub.dev/">AgentHub</a> that generates documentation for my own repo. My sand castle rebuilds itself.</p><h3>How It Works</h3><p>Whenever the pipeline is ran, it ingests all the files in my GitHub repo, passes them through the LLM while asking it to generate descriptive markdown documentation and finally raises a PR using my GitHub credentials.</p><p>For context, the code I’m documenting is the python code for the AgentHub operators. These are the modular components (called operators) which act as the building blocks of AgentHub pipelines . Each operator is it’s own short python file designed to accomplish a specific task (ex: <em>HackerNews scrapes HN posts, IngestPDF reads a pdf via and outputs the content as plain text).</em></p><p>This solution is built using operators and also documenting the very same operators. Hopefully, this isn’t too confusing.</p><p>Here’s my pipeline on AgentHub:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*SOrBcyj_1R6BJNYpPwed2w.png" /></figure><h4>Read GitHub Files:</h4><p>First I need to scrape the contents of my files from GitHub. I use the “Read files from GitHub” operator for this. It returns the file names along with the file contents in plain text.</p><pre>def read_github_files(self, params, ai_context):<br>    repo_name = params[&#39;repo_name&#39;]<br>    folders = params.get(&#39;folders&#39;).replace(&quot; &quot;, &quot;&quot;).split(&#39;,&#39;)<br>    file_regex = params.get(&#39;file_regex&#39;)<br>    branch = params.get(&#39;branch&#39;, &#39;master&#39;)<br><br>    g = Github(ai_context.get_secret(&#39;github_access_token&#39;))<br>    repo = g.get_repo(repo_name)<br><br>    file_names = []<br>    file_contents = []<br><br>    def file_matches_regex(file_path, file_regex):<br>        if not file_regex:<br>            return True<br><br>        return re.fullmatch(file_regex, file_path)<br><br>    def bfs_fetch_files(folder_path):<br>        queue = [folder_path]<br><br>        while queue:<br>            current_folder = queue.pop(0)<br><br>            contents = repo.get_contents(current_folder, ref=branch)<br><br>            for item in contents:<br>                if item.type == &quot;file&quot; and file_matches_regex(item.path, file_regex):<br>                    file_content = item.decoded_content.decode(&#39;utf-8&#39;)<br>                    file_names.append(item.path)<br>                    file_contents.append(file_content)<br><br>                elif item.type == &quot;dir&quot;:<br>                    queue.append(item.path)<br><br>    for folder_path in folders:<br>        bfs_fetch_files(folder_path)<br><br>    ai_context.add_to_log(f&quot;{self.declare_name()} Fetched {len(file_names)} files from GitHub repo {repo_name}:\n\r{file_names}&quot;, color=&#39;blue&#39;, save=True)<br><br>    ai_context.set_output(&#39;file_names&#39;, file_names, self)<br>    ai_context.set_output(&#39;file_contents&#39;, file_contents, self)<br>    return True</pre><h4>Ask ChatGPT:</h4><p>This is the workhorse of the pipeline. I pass the contents of each file from the previous step input/context for this “Ask ChatGPT” operator. I use the following very explicit prompt to generate the markdown documentation.</p><blockquote>Generate markdown documentation for this code. This documentation is meant to summarize the purpose and technical details of this operator.</blockquote><blockquote>Use headings to breakdown the documentation into the following sections.</blockquote><blockquote>Summary: a one sentence summary of this operators functionality.</blockquote><blockquote>Inputs: briefly describe the inputs and their purpose</blockquote><blockquote>Parameters: briefly describe params and their purpose</blockquote><blockquote>Outputs: briefly describe outputs</blockquote><blockquote>Functionality: this section summarizes the run_step and the helper functions supporting it.</blockquote><pre>def run_step(self, step, ai_context):<br>    p = step[&#39;parameters&#39;]<br>    question = p.get(&#39;question&#39;) or ai_context.get_input(&#39;question&#39;, self)<br>    # We want to take context both from parameter and input.<br>    input_context = ai_context.get_input(&#39;context&#39;, self)<br>    parameter_context = p.get(&#39;context&#39;)<br>    <br>    context = &#39;&#39;<br>    if input_context:<br>        context += f&#39;[{input_context}]&#39;<br>    <br>    if parameter_context:<br>        context += f&#39;[{parameter_context}]&#39;<br><br>    if context:<br>        question = f&#39;Given the context: {context}, answer the question or complete the following task: {question}&#39;<br><br>    ai_response = ai_context.run_chat_completion(prompt=question)<br>    ai_context.set_output(&#39;chatgpt_response&#39;, ai_response, self)<br>    ai_context.add_to_log(f&#39;Response from ChatGPT: {ai_response}&#39;, save=True)</pre><p>(<a href="https://github.com/agenthubdev/agenthub_operators/blob/main/operators/ask_chatgpt.py">source code</a>)</p><h4>Create Pull Request:</h4><p>Finally, if I had to copy the output over and raise the PR myself, this automation would be a chore. This last step takes the list of file names and file contents (markdown documentation) and creates a PR via my account.</p><pre>def run_step(<br>    self, <br>    step, <br>    ai_context : AiContext<br>  ):<br>    params = step[&#39;parameters&#39;]<br>    file_names = ai_context.get_input(&#39;file_names&#39;, self)<br>    file_contents = ai_context.get_input(&#39;file_contents&#39;, self)<br>  <br>    g = Github(ai_context.get_secret(&#39;github_access_token&#39;))<br>    repo = g.get_repo(params[&#39;repo_name&#39;])<br>    forked_repo = repo.create_fork()<br>  <br>    base_branch_name = &#39;main&#39;<br>    base_branch = repo.get_branch(base_branch_name)<br>  <br>    all_files = []<br>    contents = repo.get_contents(&quot;&quot;)<br>    while contents:<br>        file_content = contents.pop(0)<br>        if file_content.type == &quot;dir&quot;:<br>            contents.extend(repo.get_contents(file_content.path))<br>        else:<br>            file = file_content<br>            all_files.append(str(file).replace(&#39;ContentFile(path=&quot;&#39;,&#39;&#39;).replace(&#39;&quot;)&#39;,&#39;&#39;))<br>  <br>  <br>    new_branch_name = f&quot;agent_hub_{ai_context.get_run_id()}&quot;<br>    GitHubDocsWriter.create_branch_with_backoff(forked_repo, new_branch_name, base_branch.commit.sha)<br>  <br>    run_url = f&#39;https://agenthub.dev/agent?run_id={ai_context.get_run_id()}&#39;<br>  <br>    for file_name, file_content_string in zip(file_names, file_contents):<br>        file_path = file_name<br>        name = os.path.splitext(os.path.basename(file_path))[0] + &#39;.md&#39;<br>        docs_file_name = params[&#39;docs_folder_name&#39;] + &#39;/&#39; + name<br>  <br>        commit_message = f&quot;{file_path} - commit created by {run_url}&quot;<br>  <br>        if docs_file_name in all_files:<br>            file = repo.get_contents(docs_file_name, ref=base_branch_name)<br>            forked_repo.update_file(docs_file_name, commit_message, file_content_string.encode(&quot;utf-8&quot;), file.sha, branch=new_branch_name)<br>        else:<br>            forked_repo.create_file(docs_file_name, commit_message, file_content_string.encode(&quot;utf-8&quot;), branch=new_branch_name)<br>  <br>    # Create a pull request to merge the new branch in the forked repository into the original branch<br>    pr_title = f&quot;PR created by {run_url}&quot;<br>    pr_body = f&quot;PR created by {run_url}&quot;<br>  <br>    pr = repo.create_pull(<br>        title=pr_title, <br>        body=pr_body, <br>        base=base_branch_name, <br>        head=f&quot;{forked_repo.owner.login}:{new_branch_name}&quot;<br>    )<br>    <br>    ai_context.add_to_log(f&quot;Pull request created: {pr.html_url}&quot;)<br><br>@staticmethod  <br>def create_branch_with_backoff(forked_repo, new_branch_name, base_branch_sha, max_retries=3, initial_delay=5):<br>    delay = initial_delay<br>    retries = 0<br><br>    while retries &lt; max_retries:<br>        try:<br>            forked_repo.create_git_ref(ref=f&quot;refs/heads/{new_branch_name}&quot;, sha=base_branch_sha)<br>            return<br>        except Exception as e:<br>            if retries == max_retries - 1:<br>                raise e<br><br>            sleep_time = delay * (2 ** retries) + random.uniform(0, 0.1 * delay)<br>            print(f&quot;Error creating branch. Retrying in {sleep_time:.2f} seconds. Error: {e}&quot;)<br>            time.sleep(sleep_time)<br>            retries += 1</pre><p>GPT 3.5 vs GPT 4</p><p>AgentHub lets you choose what model you want to run for your pipeline. I tried both GPT-3.5-turbo and GPT4 for this task. The GPT4 docs leave less to the reader’s imagination and are much closer to what I would have written.</p><p>Here’s an example of the same, relatively complicated, operator being documented by each model.</p><h4>GPT3.5’s attempt:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L1x6dgJzb00NJTu0npncNA.png" /></figure><h4>GPT4’s attempt:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pR8mPBfEk2qtRJ1xw_GS4A.png" /></figure><h3>Conclusion</h3><p>If you have any ideas or needs for new operators I’d love to help you out!</p><p>I built AgentHub and would love to hear about any tasks you’d like automated. Feel free to <a href="https://discord.gg/SyCVmrzhCc">join the discord</a>, and follow the (very new) <a href="https://twitter.com/AgentHub_AI">AgentHub Twitter</a>.</p><p>I wanted to give a shoutout to <a href="https://www.linkedin.com/in/sam-snodgrass--/">Sam Snodgrass</a> who came up with this automation and contributed the operators to AgentHub!</p><p>One last thing, if you found this interesting I’d recommend reading <a href="https://medium.com/better-programming/placing-30-000-customer-orders-with-llms-f1f73872e2eb">my last post</a>. I automated the order desk for an importing agency using LLMs.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b6405881b1b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/automating-open-source-documentation-with-gpt4-5b6405881b1b">Creating a GitHub Documentation Bot With LLMs</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Automated a Business’ Order Fulfillment Process With LLMs]]></title>
            <link>https://medium.com/better-programming/placing-30-000-customer-orders-with-llms-f1f73872e2eb?source=rss-43cf42fafd89------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1f73872e2eb</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[gpt-3]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Max Brodeur-Urbas]]></dc:creator>
            <pubDate>Tue, 13 Jun 2023 06:31:48 GMT</pubDate>
            <atom:updated>2023-08-18T20:37:44.290Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*poOr2tIsdxhXDa5KYsJrUw.png" /></figure><p>I was introduced to an alcohol distribution business that was manually processing over 30,000 orders placed via email annually. Here’s how I used <a href="https://www.agenthub.dev/">AgentHub</a> to automate the ordering process with LLMs and the steps to do it yourself with no code.</p><h3>The Problem</h3><p>On any given day, this company’s inbox is flooded with emails from liquor stores or restaurants placing bulk alcohol orders. Each email is its own time-consuming puzzle. Does the email include their customer ID? Did they bother to list the item ID for any of the SKUs? Are the items in stock? Should a discount be applied?</p><p>A team of humans operating the order desk has to ask themselves these questions for each email. Any missing information requires combing through internal PDFs to fill in the blanks. They’re converting emails of varying quality to clicks in their order placement software for hours every day. On top of being extremely tedious, staffing an order desk team is expensive and acts as a bottleneck as they scale.</p><h3>The Solution</h3><p>I created two GPT4-powered pipelines that emulate the employees&#39; end-to-end workflow. An initial pipeline ingests and understands orders. The next takes action on each item.</p><p>Splitting the solution in two allows a human to sit in the middle and oversee the daily orders. This provides a sense of control while still reducing their workload by over 95%.</p><ul><li><strong>Pipeline 1</strong>: Read all emails in their inbox, extract provided info, fill in the blanks using their internal PDFs and Excel sheets. Send a summary email describing each new order to the order desk operator. Every order summary comes with an “Approve” link, which triggers pipeline 2 for that order.</li><li><strong>Pipeline 2</strong>: This pipeline places the order in its internal system and then automatically sends a confirmation email to the customer.</li></ul><p>For the sake of this article, I’ll be focusing on pipeline 1. This is where the real magic happens, and LLMs make a (Medium-article-worthy) difference.</p><h3>How It Works</h3><p>This solution was built using <a href="https://www.agenthub.dev/">AgentHub,</a> a low-code solution for creating AI pipelines. Each pipeline consists of modular components called operators.</p><blockquote>Full disclosure, I’m one of the creators of AgentHub, so I may be biased, but I think it’s the most efficient way to automate your business with AI.</blockquote><p>Put simply, the pipeline is a series of specific GPT4 queries saturated in a business-specific context. It consists of 26 operators. Five of these operators are AI-powered. The rest are scaffolding needed to manipulate and manage context. I’ll break it down into its three main sections.</p><h4>Email reading</h4><p>Step one is to process all new orders which appear in the company’s order desk inbox. All unread emails and attachments are passed into the LLM to extract the key information required to place the order.</p><ol><li><strong>Gmail reader</strong>: scrapes all unread emails from your inbox and splits the body from the attachments. If attachments are present, they’re almost always PDFs containing order details.</li><li><strong>Ingest PDF</strong>: reads the PDF and converts its content to a nicely formatted piece of text.</li><li><strong>Ask ChatGPT</strong>: This operator takes context from upstream operators and injects it into your prompt. In this case, the context is the formatted email string (with email and PDF content) and the prompt commanding the LLM to populate a predefined JSON with values from the email.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*19VFxSwjLDMYGccEGMpGvQ.png" /><figcaption>Email reading pipeline section</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*nFA-pxle40nki6ytmEh1NA.png" /><figcaption>Email reading pipeline section (continued)</figcaption></figure><h4>Context-saturated prompting</h4><p>This is my favourite part. Once an order reaches this stage, we need to add any missing information and validate correctness just like an employee would. We use the LLM for this and leave no room for hallucinations by passing all relevant context into the prompt.</p><p>I like to compare this to asking a student about a key concept in their textbook while pointing to the exact page and paragraph that contains the answer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*80U7zzSGhQGKIvoqhjLCng.png" /><figcaption>“There it is. That’s the answer right there. You can’t miss it… Good job!“</figcaption></figure><p>The utility of the pipeline depends on the student answering correctly. Three variables contribute to the student’s success.</p><p>How clear is the question? -&gt; <em>How explicit is your prompt?</em></p><p>Are you pointing to the correct paragraph? -&gt; <em>How relevant is the context you’re providing?</em></p><p>Finally, how smart is the student? -&gt; <em>How powerful is your LLM?</em></p><p>I’m using GPT4 (might as well use the valedictorian if we can), but if your question is clear enough and you’re pointing to the most relevant paragraph, any student should be able to ace the question reliably enough to generate significant value for the business.</p><p>The following pipeline section illustrates one of these very specific, context-saturated prompts. I’m asking the LLM to ensure the customer name and ID match while feeding the most relevant results from a 162-page PDF of customer information.</p><ol><li><strong>Full-Text Search (FTS)</strong>: This is the metaphorical paragraph-pointing finger. It takes a large body of text, which in our case is a PDF, and searches through it for the excerpts most relevant to the query. In this image, our query is the customer name and the customer we currently have for the order. It’s likely we only have one of the two. The PDF lines referring to this customer will be returned as context for the LLM query.</li><li><strong>Ask ChatGPT</strong>: Now that we have all info about the customer from our PDF search, the LLM can easily make sure the values match. Setting the values to null if it’s unsure.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wnxz8uZtYYCDV3Kv1l8XfQ.png" /><figcaption>Context saturated prompt pipeline section</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*HeCkZ4wGLWXPRpiMJkYzbw.png" /><figcaption>Context-saturated prompt pipeline section (continued)</figcaption></figure><p>We repeat this prompting pattern for every key question an employee would ask themselves while placing an order.</p><h4>Summarization</h4><p>Finally, take the data from each processed order and pass it in as context so GPT4 can summarize all orders.</p><p><strong>Ask ChatGPT</strong>: We’re asking the LLM to summarize the orders using valid HTML so the resulting email can be more dynamic and include formatted links.</p><p><strong>Gmail sender</strong>: this operator is set up to send emails via the AgentHub notifications account. All you need to do is pass in text and decide whether you want the email sent as HTML—no passwords required.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VGHFg5v1cLl3utLcP5Hcwg.png" /><figcaption>Final operators in the pipeline to generate a summary email.</figcaption></figure><h3>Results</h3><p>Here’s an example run for two incoming orders. The first is a standard purchase order from a customer that refers to a PDF for details. I won’t include it to avoid exposing a customer’s information. I wrote this second one to be extremely vague.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UD1h3Cmr54Qzbv6KK3WYeA.png" /></figure><p>Here’s the summary email of both orders generated by the LLM. You could ask it to have a bit more personality if you wanted, but I appreciated the directness after using it for a while.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*tPAKizXUNpu2M43JeBTC2w.png" /><figcaption>Summary email of two orders (sensitive info deleted using inspect tool)</figcaption></figure><p>The first order was very straightforward, as the LLM could decipher all the relevant info from the order PDF. The second was tricky since it had no PDF, customer ID, or item ID. It didn’t even mention the winery that sells the “hush rose.” The LLM acted like a senior order desk employee and looked up all info needed to place the order.</p><ul><li>Customer ID: it used the signature “Tommy from the Gull” to infer this customer works at “The Gull.” The full-text search found this customer info in the internal PDF, and the LLM was able to assign the correct ID</li><li>Item ID: the email requested the “hush rose.” Once again, the full-text search found all item info related to this phrase, and the LLM assigned the exact item ID.</li></ul><h3>Key Learnings</h3><p><strong>Context is all you need</strong>: The question you ask your LLM is only as strong as the context you provide alongside it. “Context Engineer” feels like a more appropriate moniker for someone trying to build useful LLM applications. Determining the most relevant context for your prompt and how to access it efficiently is the real challenge.</p><p><strong>Familiarity with the problem outweighs technical ability:</strong> If I was contracting someone to automate a part of my business, I’d be looking for someone who knows the industry over the best engineer.</p><p>While building, the only orders my pipelines would fail were when I would have also failed to understand the order. Details, like knowing a SKU number can be called a CSPC number, among many other important morsels of knowledge, were learned by immersing myself in the problem.</p><p>The more time I spent with the customer, the better the solution. Making improvements to the pipeline was trivial since almost all tweaks were to the natural language prompts. Additionally, if I ever needed to add features to an operator, it was only a ChatGPT prompt away.</p><h3>How To Build Your Own Automation</h3><p>You can visit <a href="https://www.agenthub.dev/">AgentHub </a>and build your own automation right now. All you need is an OpenAI API key and a basic understanding of LLMs (if any).</p><p>For inspiration, here’s a <a href="https://www.agenthub.dev/pipeline?agent_id=pdMpjLjgbMjHnMTqsPG2jR">pipeline that automates my Twitter account</a> 🐦 (an <a href="https://medium.com/p/de53f5e519ba">article</a> I wrote explaining it).</p><p>The exact operator you need for your pipeline may not exist just yet. We’d highly encourage you to join the <a href="https://discord.gg/SyCVmrzhCc">Discord</a> if you need our help to make it a reality.</p><p>I’d love to hear about any automation you’re trying to build and lend a helping hand if needed. Feel free to reach out to me (max@agenthub.dev) or my co-founder Misha (misha@agenthub.dev) anytime.</p><p>Thanks for reading 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1f73872e2eb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/placing-30-000-customer-orders-with-llms-f1f73872e2eb">How I Automated a Business’ Order Fulfillment Process With LLMs</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Autonomous Twitter Account with LLMs]]></title>
            <link>https://medium.com/better-programming/building-an-autonomous-twitter-account-with-llms-de53f5e519ba?source=rss-43cf42fafd89------2</link>
            <guid isPermaLink="false">https://medium.com/p/de53f5e519ba</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[gpt-4]]></category>
            <category><![CDATA[twitter]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Max Brodeur-Urbas]]></dc:creator>
            <pubDate>Fri, 19 May 2023 20:57:23 GMT</pubDate>
            <atom:updated>2023-08-18T20:29:56.005Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RGgIt_4eB1kexVKiH4yIXg.png" /></figure><p>I created my own Twitter bot using Hacker News posts, the GPT-4 API, and scheduled CRON jobs. Check out its tweets <a href="https://twitter.com/eloonsAlt">here</a>.</p><p>Setting up your own only takes a few minutes. Here’s how I did it and what I learned.</p><h3>How It Works</h3><p>At the top of every hour, my bot browses the front pages of <a href="https://news.ycombinator.com/">Hacker News</a> and picks the best post based on my interests. It then reads the article and comes up with its own opinion, sharing it straight to Twitter alongside the link.</p><p>The bot is an LLM-powered pipeline performing the above task using independent modular components (<em>operators</em>). Scheduled CRON jobs are used to trigger it so it can run as often as you’d like. Here’s a rundown of each operator.</p><h3>Technical Details</h3><p>Note: Skip this section if you’re not interested in the implementation. I explain how to create your own no-code Twitter bot later on in the article.</p><h4><strong>Scraping Hacker News</strong></h4><p>HN felt like a great place to start sourcing articles because the front pages are curated by a group of harsh but very thoughtful critics.</p><p>(Edit: I should have used the <a href="https://github.com/HackerNews/API">HackerNews API</a>. Pure web scraping works fine in this case but the API would have been easier and more dynamic)</p><p>I used the <a href="https://beautiful-soup-4.readthedocs.io/en/latest/">Beautiful Soup python library</a> to convert posts from the first n pages into a dictionary of titles and links.</p><pre>def scrape_hacker_news(self, params, ai_context):<br>    keywords = params.get(&#39;keywords&#39;, [])<br>    num_pages = int(params.get(&#39;num_pages&#39;, 1))  # Convert to int here<br>    excluded_words = [&#39;AskHN&#39;, &#39;ShowHN&#39;, &#39;LaunchHN&#39;]<br><br>    if num_pages &gt; 5:<br>      ai_context.add_to_log(f&quot;Maximum limit of 5 pages exceeded. Please provide a number up to 5.&quot;)<br>      return<br><br>    title_link_dict = {}<br><br>    for page_num in range(1, num_pages + 1):<br>      response = requests.get(f&#39;https://news.ycombinator.com/?p={page_num}&#39;)<br>      bs = BeautifulSoup(response.text, &quot;html.parser&quot;)<br>      posts = bs.select(&#39;tr.athing&#39;)  # select each post<br><br>      for post in posts:<br>        title_element = post.select_one(&#39;.titleline &gt; a&#39;)  # select the title element within the post<br>        if title_element:<br>            title = title_element.text<br>            link = title_element[&#39;href&#39;]<br><br>            # Check if any keyword is in the title (if keywords are provided)<br>            if keywords and not any(keyword.lower() in title.lower() for keyword in keywords):<br>                continue<br><br>            # Check if none of the excluded words are in the title<br>            if any(excluded_word in title for excluded_word in excluded_words):<br>                continue<br><br>            title_link_dict[title] = link</pre><p>I filtered out posts containing “AskHN”, “ShowHN ”or “LaunchHN ”flares to ignore any discussion threads.</p><h4><strong>Choosing the best post</strong></h4><p>Here I wanted to emulate how I actually scroll through posts. It’s pretty shallow but if the title is enough to grab my interest then it should be enough for my bot. I concatenate all the titles into a single string and ask the LLM to pick the most relevant based on my prompt.</p><p>An example being, “Most interesting article for AI and tech enthusiasts”. You can tailor your prompt for any niche you want to target.</p><pre>def find_best_post(self, params, ai_context):<br>    query = params.get(&#39;query&#39;, &#39;&#39;)<br>    posts = ai_context.get_input(&#39;title_link_dict&#39;, self)<br>    print(&quot;posts: &quot;, posts)<br>    title_link_dict = json.loads(posts)<br>    <br>    used_links = ai_context.memory_get_list(&#39;tweeted_links&#39;)<br>    <br>    print(f&quot;used_links = {used_links}\ntitle_link_dict = {title_link_dict}&quot;)<br>    title_link_dict = {title: url for title, url in title_link_dict.items() if url not in used_links}<br>    <br>    print(title_link_dict)<br>    # Converting titles into a context string<br>    context_string = &#39;, &#39;.join(title_link_dict.keys())<br>    <br>    ai_context.add_to_log(f&quot;Analyzing {len(title_link_dict)} potential post(s).&quot;, self)<br>    <br>    # Final prompt string<br>    message = f&quot;From the following post titles: {context_string}, pick the post that most closely reflects this desire: {query}? Return the title of the post selected and nothing else.&quot;<br>    <br>    # Here you can pass the prompt to your function<br>    msgs = [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: message}]<br>    best_post_title = ai_context.run_chat_completion(msgs=msgs)<br>    <br>    # Check if the title exists in the dictionary<br>    if best_post_title not in title_link_dict and best_post_title.endswith(&#39;.&#39;):<br>        best_post_title = best_post_title[:-1]  # Remove the last character (the period)<br>    <br>    best_post_link = title_link_dict.get(best_post_title, &#39;&#39;)<br>    <br>    ai_context.add_to_log(f&quot;The most relevant post to your query is titled: {best_post_title}. With Link: {best_post_link}&quot;, self)<br>    <br>    ai_context.set_output(&#39;best_post_link&#39;, best_post_link, self)</pre><h4>Read the article</h4><p>Now that I’ve identified the article I’d want to read, I once again use Beautiful Soup to scrape all content from the page/article.</p><pre>def ingest(self, params, ai_context):<br>    data_uri = params.get(&#39;data_uri&#39;, None)<br>    if not data_uri:<br>        data_uri = ai_context.get_input(&#39;input_url&#39;, self)<br>    ai_context.storage[&#39;ingested_url&#39;] = data_uri<br>    if self.is_url(https://medium.com/data_uri):<br>        text = self.scrape_text(data_uri)<br>        ai_context.set_output(&#39;uri_content&#39;, text, self)<br>        ai_context.add_to_log(f&quot;Content from {data_uri} has been scraped.&quot;)<br><br>def scrape_text(self, url):<br>    response = requests.get(url)<br>    bs = BeautifulSoup(response.text, &quot;html.parser&quot;)<br><br>    for script in bs([&quot;script&quot;, &quot;style&quot;]):<br>        script.extract()<br><br>    text = bs.get_text()<br>    lines = (line.strip() for line in text.splitlines())<br>    chunks = (phrase.strip() for line in lines for phrase in line.split(&quot;  &quot;))<br>    text = &quot;\n&quot;.join(chunk for chunk in chunks if chunk)<br><br>    return text</pre><h4>Index the data</h4><p>I wanted to make sure that articles of any length can be ingested. If I try to pass an entire 20-page article into my prompt I’ll overshoot the token limit.</p><p>I chunked the content into more manageable pieces and used OpenAI’s embedding API. I stored this info in a dictionary with embeddings as keys and chunked text as values. I can then retrieve the most relevant chunk of context for a given prompt if I embed my prompt and calculate the distance between each chunk.</p><p>(This embedded data should ideally be stored in a Vector Database for scalability and speed. For the sake of the demo I stored it in memory)</p><pre>def get_embedding(self, text_or_tokens):<br>    EMBEDDING_MODEL = &#39;text-embedding-ada-002&#39;<br>    return openai.Embedding.create(input=text_or_tokens, model=EMBEDDING_MODEL)[&quot;data&quot;][0][&quot;embedding&quot;]<br>  <br>def clean_text(self, text):<br>    return text.replace(&quot;\n&quot;, &quot; &quot;)<br><br>def batched(self, iterable, n):<br>    if n &lt; 1:<br>        raise ValueError(&#39;n must be at least one&#39;)<br>    it = iter(iterable)<br>    while (batch := tuple(islice(it, n))):<br>        yield batch<br><br>def chunked_tokens(self, text, encoding_name, chunk_length):<br>    encoding = tiktoken.get_encoding(encoding_name)<br>    tokens = encoding.encode(text)<br>    chunks_iterator = self.batched(tokens, chunk_length)<br>    for chunk in chunks_iterator:<br>        decoded_chunk = encoding.decode(chunk)  # Decode the chunk<br>        yield decoded_chunk<br><br>def len_safe_get_embedding(self, text, max_tokens=EMBEDDING_CTX_LENGTH, encoding_name=EMBEDDING_ENCODING):<br>    chunk_embeddings = {}<br>    for chunk in self.chunked_tokens(text, encoding_name=encoding_name, chunk_length=max_tokens):<br>        embedding = self.get_embedding(chunk)<br>        embedding_key = tuple(embedding)  # Convert numpy array to tuple<br>        chunk_embeddings[embedding_key] = chunk<br><br>    return chunk_embeddings</pre><h4>Hybrid search</h4><p>This is where the Tweet is made. I pass in a prompt asking the agent to form a concise and interesting tweet about the article&#39;s key concepts. This operator stuffs that LLM query with the most relevant chunks using the above embedding approach.</p><p>This approach works great for very pointed questions. If you want to ask your agent about a specific quote or detail in the article, context stuffing will fetch the most relevant chunks and pipe them into your query.</p><p>For this case, a summary of chunks would actually be more useful since I’m not asking a very specific question. We added a summarization operator after I deployed the demo which I’ll use in the future.</p><pre><br>def get_embedding(self, text_or_tokens):<br>    EMBEDDING_MODEL = &#39;text-embedding-ada-002&#39;<br>    return openai.Embedding.create(input=text_or_tokens, model=EMBEDDING_MODEL)[&quot;data&quot;][0][&quot;embedding&quot;]<br><br>def cosine_distance(self, emb1, emb2):<br>    return np.dot(emb1, emb2) / (np.linalg.norm(emb1) * np.linalg.norm(emb2))<br><br>def calculate_sorted_similarities(self, query_embedding, embeddings_dict):<br>    sorted_similarities = []<br><br>    for embedding_key, text in embeddings_dict.items():<br>        embedding = np.array(embedding_key)  # Convert tuple to numpy array<br>        similarity = self.cosine_distance(query_embedding, embedding)<br>        heapq.heappush(sorted_similarities, (-similarity, embedding_key, text))<br><br>    return sorted_similarities<br><br>def num_tokens_from_string(self, string: str, model_name: str = &#39;gpt-3.5-turbo&#39;) -&gt; int:<br>    &quot;&quot;&quot;Returns the number of tokens in a text string.&quot;&quot;&quot;<br>    encoding = tiktoken.encoding_for_model(model_name)<br>    num_tokens = len(encoding.encode(string))<br>    return num_tokens<br><br>def get_max_embeddings_fit(self, sorted_similarities, initial_tokens, ai_context, model=&#39;gpt-3.5-turbo&#39;):<br>    # Since OpenAI is applying a limit to combined tokens in the input prompt and the response<br>    # we want to make sure we leave enough space for the output by not overinflating the input prompt.<br>    MIN_RESPONSE_SIZE = 250<br><br>    selected_embeddings = []<br>    total_tokens = initial_tokens + MIN_RESPONSE_SIZE<br>    token_limit = get_max_tokens_for_model(model)<br>    <br>    for similarity, embedding_key, text in sorted_similarities:<br>        text_tokens = self.num_tokens_from_string(text, model)<br>        <br>        if total_tokens + text_tokens  &lt; token_limit:<br>            total_tokens += text_tokens <br>            selected_embeddings.append(text)<br>        else:<br>            break<br>    <br>    ai_context.add_to_log(&quot;{} embeddings were fit into the prompt&quot;.format(len(selected_embeddings)))<br>    return selected_embeddings<br><br># Generate a heap of the most similar embeddings, we&#39;re unsure how many we can fit into the prompt at this point. <br>sorted_embeddings = self.calculate_sorted_similarities(query_embedding, ai_context.get_input(&#39;vector_index&#39;, self))<br># Format the message and determine how many tokens our contextless prompt is<br>message = f&quot;Given the following context, and any prior knowledge you have, {query}?&quot;<br>message_tokens = self.num_tokens_from_string(message)<br># Fit as many embeddings as we can into the prompt<br>closest_embeddings = self.get_max_embeddings_fit(<br>    sorted_similarities=sorted_embeddings, <br>    initial_tokens=message_tokens, <br>    ai_context=ai_context<br>)<br><br># Add context to message<br>closest_embeddings_str = str(closest_embeddings)<br>message += f&quot; context: {closest_embeddings_str}&quot;  <br>      <br>msgs = [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: message}]<br>ai_response = ai_context.run_chat_completion(msgs=msgs)<br>ai_context.set_output(&#39;hybrid_search_chatgpt_response&#39;, ai_response, self)<br>ai_context.add_to_log(f&#39;Response from ChatGPT + Hybrid Search: {ai_response}&#39;)</pre><h4>Tweet</h4><p>This operator interfaces with the Twitter API using the OAuth access you provided when linking your account.</p><pre>def send_tweet(self, tweet_text, url, ai_context):<br>  client = tweepy.Client(bearer_token=self.bearer_token)<br>  client = tweepy.Client(<br>      consumer_key=self.consumer_key, consumer_secret=self.consumer_secret,<br>      access_token=self.access_token, access_token_secret=self.access_token_secret<br>  )<br>  formatted_tweet_text = f&quot;{tweet_text}\n{url}&quot;<br>  <br>  # If tweet is too long, remove hashtags<br>  if self.is_over_twitter_limit(formatted_tweet_text):<br>      formatted_tweet_text = self.remove_hashtags(formatted_tweet_text)<br>  <br>  ai_context.add_to_log(f&#39;Tweeting: {formatted_tweet_text}&#39;)<br>  try:<br>      response = client.create_tweet(<br>          text=formatted_tweet_text<br>      )<br>      ai_context.add_to_log(f&quot;Tweet is live at: https://twitter.com/user/status/{response.data[&#39;id&#39;]}&quot;, color=&#39;green&#39;)<br>      <br>  except tweepy.TweepyException  as e:<br>      print(str(e))<br>      ai_context.add_to_log(f&quot;Error sending tweet: {str(e)}&quot;)</pre><h4>Scheduling a Run</h4><p>I use a CRON job to have this pipeline run at the top of every hour.</p><h3>Learnings</h3><ul><li><strong>Be careful what you wish for. </strong>Your instructions are taken as gospel so be careful asking it to be “funny” or “lighthearted”. It will make everything a joke…<strong> </strong>If it happens to consume an article about a tragedy it will definitely share it with crying laughing emojis and a bad pun.</li><li><strong>GPT4 is worth every extra penny for creating content</strong>. It can use emojis, crack jokes and pretend it has experience with the article&#39;s topic while 3.5 writes rather boring summaries. Prompting it requires a bit more subtlety, however. Asking it to be serious will make it boring, asking it to be funny will make it annoying. I’d recommend testing out individual tweets using the simpler “🐦 Single Article Twitter Bot” on AgentHub to get a feeling for your preferences.</li><li><strong>Anti-bot software throws a bit of a wrench into it’s process.</strong> Some websites like NY Times and Bloomberg have bot detection to prevent scraping. The bot can occasionally run into blockers and formulate tweets about the fact that it’s been detected. These are probably my favorite tweets to wake up to after a night of it autonomously tweeting.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*9TrVfcuhWzw2kqpnOBzZMQ.png" /></figure><h3>Deploy Your Own Bot with No Code</h3><p>To run this bot on your own Twitter account follow the following steps. This Twitter bot is published on AgentHub under “Hands Free Tweeter”.</p><ul><li>Visit <a href="https://www.agenthub.dev/?fuel_source_id=1ce2cdda-304d-435d-a823-4a9c507bb7ea">this link</a> to use our OpenAI API tokens with GPT-4 access.</li><li>Click on the published agent.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*TnhXWpV5PvX5mY1eL1zWGQ.png" /><figcaption>Autonomous Tweet Bot on Published on AgentHub</figcaption></figure><ul><li>Click “Run Agent” to have it create a single post for you</li><li>Link your Twitter account if you haven’t yet.</li><li>Click “Schedule Agent” near the bottom of the page.</li><li>Enter your OpenAI API token (<em>you can skip this step, I put my own token in with GPT4 access so can try it out for free</em>).</li></ul><h3>Contributing</h3><p>I’m sure the average person reading this article can come up with a more useful agent than this Twitter bot. I’d love to see what others are able to do. If you want to get involved you can:</p><ol><li>Join our <a href="https://discord.gg/xtbrafmzC7">Discord</a>: This is probably the best way to get in touch with us and hear about daily updates.</li><li>Create your own agents: Give <a href="https://www.agenthub.dev/?fuel_source_id=1ce2cdda-304d-435d-a823-4a9c507bb7ea">AgentHub </a>a try. Once you get one working you can hit the publish button to get your creation posted live on the platform.</li></ol><p><a href="https://twitter.com/MaxBrodeurUrbas">dm me on Twitter</a> if you have any questions. Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de53f5e519ba" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/building-an-autonomous-twitter-account-with-llms-de53f5e519ba">Building an Autonomous Twitter Account with LLMs</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>