<?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 Sammy-Jo Wymer on Medium]]></title>
        <description><![CDATA[Stories by Sammy-Jo Wymer on Medium]]></description>
        <link>https://medium.com/@sammyjowymerpsych?source=rss-9d12aafc9fb1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*GssSGjMVOOxYMVy7</url>
            <title>Stories by Sammy-Jo Wymer on Medium</title>
            <link>https://medium.com/@sammyjowymerpsych?source=rss-9d12aafc9fb1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 10:46:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sammyjowymerpsych/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[Turning Go Code into Interactive Diagrams with React and D3.js]]></title>
            <link>https://medium.com/codex/turning-go-code-into-interactive-diagrams-with-react-and-d3-js-5b1ab6588693?source=rss-9d12aafc9fb1------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b1ab6588693</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Sammy-Jo Wymer]]></dc:creator>
            <pubDate>Fri, 26 Sep 2025 09:49:46 GMT</pubDate>
            <atom:updated>2025-09-29T10:45:36.816Z</atom:updated>
            <content:encoded><![CDATA[<p>In this walkthrough, we’ll build a tool that takes a Go repository and automatically generates an interactive diagram of its function calls. By the end, you’ll have a working application that helps you (and your team) understand codebases at a glance.</p><p><strong><em>Note: These words are my own and not those of AI :)</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mhLvzXQhAdj4wn7Duh6hzA.jpeg" /><figcaption>Photo by Aleksandr Neplokhov: <a href="https://www.pexels.com/photo/group-of-people-gathering-near-frees-standing-flow-letters-1238965/">https://www.pexels.com/photo/group-of-people-gathering-near-frees-standing-flow-letters-1238965/</a></figcaption></figure><h4>Prerequisites</h4><p><a href="https://go.dev/">Go<br></a><a href="https://react.dev/">React</a><br>D<a href="https://d3js.org/">3.js</a><br><a href="https://vite.dev/">Vite</a><br>A basic understanding of Go and React.</p><h4>Introduction</h4><p>In this walkthrough, we’re going to create a tool which takes in a Go code repository and <strong>generates an interactive diagram showing the flow of function calls</strong>. For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q4rWy3Z9pYfOV3jHI8Oi-w.png" /><figcaption>Example function flow diagram</figcaption></figure><h4>Setup</h4><p>Create a new repository and call it whatever you like (I called it go-flow). Within this repository, create two folders: frontend and backend.</p><h4>Backend Setup</h4><p>Navigate to the backend folder (e.g. cd backend in your terminal) and initialise the repository with: go mod init &lt;github-repo-address&gt;/goflow</p><p>For example, my command would be: go mod init <a href="https://github.com/wymersam">https://github.com/wymersam</a>/goflow</p><p>This will generate the go.mod and go.sum files.</p><p>Within the backend folder, we’re going to create our first file called main.go. This file sets up a <strong>server endpoint to receive data that a user uploads</strong> (e.g. a code repository).</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;log&quot;<br> &quot;net/http&quot;<br> &quot;os&quot;<br><br>// update this with your github url<br> &quot;github.com/wymersam/goflow/handlers&quot;<br>)<br><br>// we need to enable CORS since we&#39;ll be running the frontend on a<br>// different port. Without this, our browser may block the connection.<br>func enableCORS(next http.HandlerFunc) http.HandlerFunc {<br> return func(w http.ResponseWriter, r *http.Request) {<br>  w.Header().Set(&quot;Access-Control-Allow-Origin&quot;, &quot;*&quot;)<br>  w.Header().Set(&quot;Access-Control-Allow-Methods&quot;, &quot;GET, POST, OPTIONS&quot;)<br>  w.Header().Set(&quot;Access-Control-Allow-Headers&quot;, &quot;Content-Type&quot;)<br><br>  if r.Method == http.MethodOptions {<br>   w.WriteHeader(http.StatusOK)<br>   return<br>  }<br>  next(w, r)<br> }<br>}<br><br>// set up a basic Go server that can receive uploaded code from a user<br>// at the /parse endpoint.<br>func main() {<br> http.HandleFunc(&quot;/parse&quot;, enableCORS(handlers.HandleRepoParse))<br> http.HandleFunc(&quot;/health&quot;, func(w http.ResponseWriter, r *http.Request) {<br>  fmt.Fprintln(w, &quot;GoFlow server is running!&quot;)<br> })<br><br> port := os.Getenv(&quot;PORT&quot;)<br> if port == &quot;&quot; {<br>  port = &quot;8080&quot;<br> }<br><br> fmt.Println(&quot;Server listening on port&quot;, port)<br> log.Fatal(http.ListenAndServe(&quot;:&quot;+port, nil))<br>}</pre><p>Within the backend folder, create a folder called handlers.</p><p>Within the handlers folder, we’re going to create our next file called parse.go, which will handle the logic for this /parse endpoint. The purpose of this file will be to <strong>receive a zipped code repository and establish what the function call relationships are within the code</strong>. Each step is describe in the code comments:</p><pre>package handlers<br><br>import (<br> &quot;archive/zip&quot;<br> &quot;bytes&quot;<br> &quot;encoding/json&quot;<br> &quot;go/ast&quot;<br> &quot;go/parser&quot;<br> &quot;go/token&quot;<br> &quot;io&quot;<br> &quot;io/fs&quot;<br> &quot;net/http&quot;<br> &quot;os&quot;<br> &quot;path/filepath&quot;<br> &quot;sort&quot;<br> &quot;strings&quot;<br>)<br><br>// the function call relationships will be returned as a JSON object <br>// representing the functions as nodes and their connections as links.<br>type ParseResponse struct {<br> Nodes []string `json:&quot;nodes&quot;`<br> Links []Link   `json:&quot;links&quot;`<br>}<br><br>type Link struct {<br> Source string `json:&quot;source&quot;`<br> Target string `json:&quot;target&quot;`<br>}<br><br>func HandleRepoParse(w http.ResponseWriter, r *http.Request) {<br>// error handling to ensure only POST requests are allowed.<br> if r.Method != http.MethodPost {<br>  http.Error(w, &quot;Only POST allowed&quot;, http.StatusMethodNotAllowed)<br>  return<br> }<br><br>// error handling for file size. Files which are too big will not be processed.<br> err := r.ParseMultipartForm(100 &lt;&lt; 20) // 100MB max<br> if err != nil {<br>  http.Error(w, &quot;Failed to parse form&quot;, http.StatusBadRequest)<br>  return<br> }<br><br>// error handling for missing upload.<br> file, _, err := r.FormFile(&quot;repo&quot;)<br> if err != nil {<br>  http.Error(w, &quot;Missing repo file&quot;, http.StatusBadRequest)<br>  return<br> }<br> defer file.Close()<br><br> // load the uploaded ZIP file into memory so it can be unzipped and processed.<br> buf := new(bytes.Buffer)<br> _, err = io.Copy(buf, file)<br> if err != nil {<br>  http.Error(w, &quot;Failed to read zip file&quot;, http.StatusInternalServerError)<br>  return<br> }<br><br>// create a temporary folder to extract and analyse the Go files.<br> tmpDir, err := os.MkdirTemp(&quot;&quot;, &quot;gorepo&quot;)<br> if err != nil {<br>  http.Error(w, &quot;Failed to create temp dir&quot;, http.StatusInternalServerError)<br>  return<br> }<br> defer os.RemoveAll(tmpDir)<br><br>// error handling for issues extracting the files.<br> err = unzip(buf.Bytes(), tmpDir)<br> if err != nil {<br>  http.Error(w, &quot;Failed to unzip repo&quot;, http.StatusInternalServerError)<br>  return<br> }<br><br>// keep track of things such as line numbers in the source code files. <br>// this allows us to link syntax elements to their location in the code.<br> fset := token.NewFileSet()<br> var files []*ast.File // ASTs = abstract syntax trees<br><br>// go through all files and folders inside the extracted repo and skip<br>// any files that doesn’t end in .go.<br> err = filepath.WalkDir(tmpDir, func(path string, d fs.DirEntry, err error) error {<br>  if err != nil || d.IsDir() || !strings.HasSuffix(path, &quot;.go&quot;) {<br>   return nil<br>  }<br>// read the contents of each file and parse each file into an AST node.<br>  src, err := os.ReadFile(path)<br>  if err != nil {<br>   return nil<br>  }<br>  node, err := parser.ParseFile(fset, path, src, parser.AllErrors)<br>  if err == nil {<br>   files = append(files, node)<br>  }<br>  return nil<br> })<br> if err != nil {<br>  http.Error(w, &quot;Failed to walk files&quot;, http.StatusInternalServerError)<br>  return<br> }<br><br>// this is a function we will create in the next step. Hold tight :)<br> funcMap, err := BuildCodeFlowDiagram(files, fset)<br> if err != nil {<br>  http.Error(w, &quot;Failed to analyse code&quot;, http.StatusInternalServerError)<br>  return<br> }<br><br>// create a JSON response that represents all functions as nodes and their <br>// calls as links. This will allow our frontend to visualise the function call<br>// graph.<br> nodeSet := make(map[string]struct{})<br> var links []Link<br><br> for funcName, info := range funcMap {<br>  nodeSet[funcName] = struct{}{}<br>  for _, call := range info.Calls {<br>   nodeSet[call] = struct{}{}<br>   links = append(links, Link{Source: funcName, Target: call})<br>  }<br> }<br><br> var nodes []string<br> for n := range nodeSet {<br>  nodes = append(nodes, n)<br> }<br> sort.Strings(nodes)<br><br> resp := ParseResponse{<br>  Nodes: nodes,<br>  Links: links,<br> }<br><br> w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br> json.NewEncoder(w).Encode(resp)<br>}<br><br>// a helper function to unzip the .zip file the user uploads.<br>func unzip(data []byte, dest string) error {<br> r, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))<br> if err != nil {<br>  return err<br> }<br> for _, f := range r.File {<br>  fpath := filepath.Join(dest, f.Name)<br>  if f.FileInfo().IsDir() {<br>   os.MkdirAll(fpath, os.ModePerm)<br>   continue<br>  }<br>  if err := os.MkdirAll(filepath.Dir(fpath), os.ModePerm); err != nil {<br>   return err<br>  }<br>  outFile, err := os.Create(fpath)<br>  if err != nil {<br>   return err<br>  }<br>  rc, err := f.Open()<br>  if err != nil {<br>   outFile.Close()<br>   return err<br>  }<br>  _, err = io.Copy(outFile, rc)<br>  outFile.Close()<br>  rc.Close()<br>  if err != nil {<br>   return err<br>  }<br> }<br> return nil<br>}</pre><p>Nice! Now let’s create that BuildCodeFlowDiagram function.</p><p>Still within the handlers folder, create a new file called diagram.go:</p><pre>package handlers<br><br>import (<br> &quot;bytes&quot;<br> &quot;go/ast&quot;<br> &quot;go/printer&quot;<br> &quot;go/token&quot;<br>)<br><br>// represents a function call graph: function =&gt; list of functions it calls.<br>type CallGraph map[string][]string<br>type FunctionInfo struct {<br> Name       string<br> Calls      []string<br> SourceCode string<br> Pos        token.Position<br>}<br><br>// take a parsed Go function and return its original source code as a string.<br>func getFuncSource(node *ast.FuncDecl, fset *token.FileSet) (string, error) {<br> var buf bytes.Buffer<br> err := printer.Fprint(&amp;buf, fset, node)<br> if err != nil {<br>  return &quot;&quot;, err<br> }<br> return buf.String(), nil<br>}<br><br>// walk through all the parsed Go files and extract the function’s name,<br>// the source code of the function, a list of other functions that it <br>// calls, and the source position (file and line number) of the function.<br>func BuildCodeFlowDiagram(files []*ast.File, fset *token.FileSet) (map[string]FunctionInfo, error) {<br> funcMap := make(map[string]FunctionInfo)<br><br> for _, node := range files {<br>  ast.Inspect(node, func(n ast.Node) bool {<br>   fn, ok := n.(*ast.FuncDecl)<br>   if !ok || fn.Body == nil {<br>    return true<br>   }<br>   funcName := fn.Name.Name<br><br>   src, err := getFuncSource(fn, fset)<br>   if err != nil {<br>    return true<br>   }<br><br>   calls := []string{}<br>   ast.Inspect(fn.Body, func(bn ast.Node) bool {<br>    call, ok := bn.(*ast.CallExpr)<br>    if !ok {<br>     return true<br>    }<br>    switch fun := call.Fun.(type) {<br>    case *ast.Ident:<br>     calls = append(calls, fun.Name)<br>    case *ast.SelectorExpr:<br>     calls = append(calls, fun.Sel.Name)<br>    }<br>    return true<br>   })<br><br>// collect all the information in a map where each function name points to <br>// its details.<br>   funcMap[funcName] = FunctionInfo{<br>    Name:       funcName,<br>    Calls:      calls,<br>    SourceCode: src,<br>    Pos:        fset.Position(fn.Pos()),<br>   }<br><br>   return true<br>  })<br> }<br><br> return funcMap, nil<br>}</pre><p>That’s the backend done! Not bad, ey?</p><h4>Frontend Setup</h4><p>Our frontend code will be written in React, therefore we need to set up the frontend folder accordingly.</p><p>In the terminal, make sure you’re in the project root, navigate to the frontend folder and run the following to generate a package.json:</p><p>npm init -y</p><p>This is an example of how the package.json should look:</p><pre>{<br>  &quot;name&quot;: &quot;frontend&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;&quot;,<br>  &quot;main&quot;: &quot;index.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;dev&quot;: &quot;vite&quot;,<br>    &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;<br>  },<br>  &quot;keywords&quot;: [],<br>  &quot;proxy&quot;: &quot;http://localhost:8080&quot;,<br>  &quot;author&quot;: &quot;&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;,<br>  &quot;type&quot;: &quot;commonjs&quot;,<br>  &quot;dependencies&quot;: {<br>    &quot;d3&quot;: &quot;^7.9.0&quot;,<br>    &quot;react&quot;: &quot;^19.1.0&quot;,<br>    &quot;react-dom&quot;: &quot;^19.1.0&quot;<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;@vitejs/plugin-react&quot;: &quot;^4.6.0&quot;,<br>    &quot;vite&quot;: &quot;^7.0.3&quot;<br>  }<br>}</pre><p>Staying in the frontend folder, create a file for simple Vite configuration called vite.config.ts (this is just to simplify the setup process and will allow us to run the frontend locally with npm run dev):</p><pre>import { defineConfig } from &quot;vite&quot;;<br>import react from &quot;@vitejs/plugin-react&quot;;<br><br>export default defineConfig({<br>  plugins: [react()],<br>});</pre><p>Still in the frontend folder, create a simple index.html file at the root:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>    &lt;title&gt;Go Flow&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;<br>    &lt;script type=&quot;module&quot; src=&quot;/src/index.tsx&quot;&gt;&lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Create a src folder and within this folder, add a simple index.tsx:</p><pre>import React from &quot;react&quot;;<br>import ReactDOM from &quot;react-dom/client&quot;;<br>import App from &quot;./App&quot;;<br><br>ReactDOM.createRoot(document.getElementById(&quot;root&quot;)!).render(&lt;App /&gt;);</pre><p>Still in the src folder, create another folder called components and create a file here called GoFileUploader.tsx. This file will provide the functionality for uploading a Go repository to be analysed:</p><pre>import React, { useState } from &quot;react&quot;;<br><br>// this is the type of response we expect when we send the file data to the<br>// backend we created.<br>interface ParseResponse {<br>  nodes: string[];<br>  links: { source: string; target: string }[];<br>}<br><br>interface GoFileUploaderProps {<br>  onGraphData: (data: { nodes: { id: string }[]; links: any[] }) =&gt; void;<br>}<br><br>const GoFileUploader: React.FC&lt;GoFileUploaderProps&gt; = ({ onGraphData }) =&gt; {<br>  const [loading, setLoading] = useState(false);<br>  const [error, setError] = useState&lt;string | null&gt;(null);<br><br>// we check if the user has uploaded a file and whether this file is in .zip<br>// format. If not, we return an error.<br>  const handleFileChange = (e: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {<br>    const file = e.target.files?.[0];<br>    if (!file) return;<br><br>    if (!file.name.endsWith(&quot;.zip&quot;)) {<br>      alert(&quot;Please select a ZIP file (.zip)&quot;);<br>      return;<br>    }<br><br>    setError(null);<br>    setLoading(true);<br><br>// create a new form data object (the key will be &quot;repo&quot; with the value of<br>// the &quot;file&quot; the user uploaded). We then send this form data object to our<br>// backend &#39;/parse&#39;, which will analyse the repository and map the function<br>// connections.<br>    const formData = new FormData();<br>    formData.append(&quot;repo&quot;, file);<br><br>    fetch(&quot;http://localhost:8080/parse&quot;, {<br>      method: &quot;POST&quot;,<br>      body: formData,<br>    })<br>      .then(async (response) =&gt; {<br>        if (!response.ok) {<br>          throw new Error(await response.text());<br>        }<br>        return response.json() as Promise&lt;ParseResponse&gt;;<br>      })<br>      .then((data) =&gt; {<br>        setLoading(false);<br><br>        onGraphData({<br>          nodes: data.nodes.map((id) =&gt; ({ id })),<br>          links: data.links,<br>        });<br>      })<br>      .catch((err) =&gt; {<br>        setError(err.message);<br>        setLoading(false);<br>      });<br>  };<br><br>  return (<br>    &lt;div className=&quot;container&quot;&gt;<br>      &lt;h2&gt;Upload Go repository (.zip)&lt;/h2&gt;<br>      &lt;input type=&quot;file&quot; accept=&quot;.zip&quot; onChange={handleFileChange} /&gt;<br>      {loading &amp;&amp; &lt;p className=&quot;loading-text&quot;&gt;Processing file...&lt;/p&gt;}<br>      {error &amp;&amp; &lt;p className=&quot;error-text&quot;&gt;{error}&lt;/p&gt;}<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default GoFileUploader;</pre><p>Let’s see how this component looks. In src, create a file called App.tsx with the following contents:</p><pre>import React from &quot;react&quot;;<br>import GoFileUploader from &quot;./components/GoFileUploader&quot;;<br><br>const App: React.FC = () =&gt; {<br>  const [graphData, setGraphData] = React.useState&lt;{<br>    nodes: { id: string }[];<br>    links: any[];<br>  } | null&gt;(null);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Go Function Call Graph&lt;/h1&gt;<br>      &lt;GoFileUploader onGraphData={setGraphData} /&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default App;</pre><p>In your terminal, make sure you’re in the project root and run:</p><p>cd backend<br>go run .</p><p>Open another terminal, also in the project root and run:</p><p>cd frontend<br>npm run dev</p><p>Navigate to <a href="http://localhost:5173/">http://localhost:5173</a> and you should see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*bPUwLi6reoHpSFJytzjLow.png" /><figcaption>User Interface (UI) of the File Uploader component</figcaption></figure><p>You’ll be able to select a file to upload but nothing else will happen just yet.</p><p>We will now add the Diagram component, which is the real star of the show. In this component, we’ll utilise the d3.js package to generate a <strong>lovely, interactive function flow diagram to easily map functions and the functions they call</strong>.</p><p>In the components folder, create a new file called Diagram.tsx with the following contents:</p><pre>import React, { useEffect, useRef } from &quot;react&quot;;<br>import * as d3 from &quot;d3&quot;;<br><br>// the NodeType represents a function, where the &quot;id&quot; is the function name.<br>type NodeType = {<br>  id: string;<br>  x?: number;<br>  y?: number;<br>  fx?: number | null;<br>  fy?: number | null;<br>};<br><br>// the LinkType is the function that is called by another function.<br>type LinkType = { source: string | NodeType; target: string | NodeType };<br><br>// the DiagramProps show how the diagram will be built (e.g. with the functions<br>// and the functions they call).<br>type DiagramProps = {<br>  nodes: NodeType[];<br>  links: LinkType[];<br>};<br><br>// this function takes in the nodes and links (explained above) <br>// and builds a graph using D3 inside an SVG element.<br>const Diagram: React.FC&lt;DiagramProps&gt; = ({ nodes, links }) =&gt; {<br>  const svgRef = useRef&lt;SVGSVGElement | null&gt;(null);<br>  const gRef = useRef&lt;SVGGElement | null&gt;(null);<br><br>  useEffect(() =&gt; {<br>// stops if there are no nodes/links or refs aren&#39;t ready.<br>    if (!nodes.length || !links.length || !svgRef.current || !gRef.current)<br>      return;<br><br>// selects the SVG and &lt;g&gt; elements with D3.<br>    const svg = d3.select(svgRef.current);<br>    const g = d3.select(gRef.current);<br><br>// clears out any previous graph elements before re-rendering.<br>    svg.selectAll(&quot;g &gt; *&quot;).remove(); <br><br>    const width = svgRef.current.clientWidth;<br>    const height = svgRef.current.clientHeight;<br><br>// enables zoom and pan on the entire SVG.<br>    svg.call(<br>      d3.zoom&lt;SVGSVGElement, unknown&gt;().on(&quot;zoom&quot;, (event) =&gt; {<br>        g.attr(&quot;transform&quot;, event.transform);<br>      })<br>    );<br><br>// creates a &quot;force simulation&quot; — this is D3’s built-in physics engine<br>// it calculates how nodes and links should move, using forces like<br>// attraction, repulsion, and centering.<br>    const simulation = d3<br>      .forceSimulation(nodes as any)<br>      .force(<br>        &quot;link&quot;,<br>        d3<br>          .forceLink(links as any)<br>          .id((d: any) =&gt; d.id)<br>          .distance(100)<br>      )<br>      .force(&quot;charge&quot;, d3.forceManyBody().strength(-300))<br>      .force(&quot;center&quot;, d3.forceCenter(width / 2, height / 2));<br><br>// tracks connections.<br>    const linkedByIndex = new Set(<br>      links.map(<br>        (d) =&gt; `${(d.source as NodeType).id}|${(d.target as NodeType).id}`<br>      )<br>    );<br><br>// checks if two nodes are directly connected.<br>    const isConnected = (a: NodeType, b: NodeType) =&gt;<br>      linkedByIndex.has(`${a.id}|${b.id}`) ||<br>      linkedByIndex.has(`${b.id}|${a.id}`);<br><br>    let selectedNode: NodeType | null = null;<br><br>// draws the links (lines between nodes).<br>    const link = g<br>      .append(&quot;g&quot;)<br>      .attr(&quot;stroke&quot;, &quot;#999&quot;)<br>      .attr(&quot;stroke-opacity&quot;, 0.6)<br>      .selectAll(&quot;line&quot;)<br>      .data(links)<br>      .join(&quot;line&quot;)<br>      .attr(&quot;stroke-width&quot;, 1.5);<br><br>// draws the nodes as circles.<br>    const node = g<br>      .append(&quot;g&quot;)<br>      .attr(&quot;stroke&quot;, &quot;#fff&quot;)<br>      .attr(&quot;stroke-width&quot;, 1.5)<br>      .selectAll&lt;SVGCircleElement, NodeType&gt;(&quot;circle&quot;)<br>      .data(nodes)<br>      .join(&quot;circle&quot;)<br>      .attr(&quot;r&quot;, 10)<br>      .attr(&quot;fill&quot;, &quot;#69b3a2&quot;)<br>// adds interactivity: click to highlight neighbours.<br>      .on(&quot;click&quot;, (event, d: NodeType) =&gt; {<br>        if (selectedNode === d) {<br>          // if the same node is clicked again then reset the view.<br>          selectedNode = null;<br>          node.style(&quot;opacity&quot;, 1);<br>          link.style(&quot;opacity&quot;, 1);<br>          label.style(&quot;opacity&quot;, 1);<br>        } else {<br>          // highlights the connected nodes/links.<br>          selectedNode = d;<br>          node.style(&quot;opacity&quot;, (o: any) =&gt;<br>            o === d || isConnected(d, o) ? 1 : 0.1<br>          );<br>          link.style(&quot;opacity&quot;, (l: any) =&gt;<br>            l.source === d || l.target === d ? 1 : 0.1<br>          );<br>          label.style(&quot;opacity&quot;, (o: any) =&gt;<br>            o === d || isConnected(d, o) ? 1 : 0.1<br>          );<br>        }<br>      })<br>// enables dragging of nodes (to manually reposition them).<br>      .call(<br>        d3<br>          .drag&lt;SVGCircleElement, NodeType&gt;()<br>          .on(&quot;start&quot;, (event, d) =&gt; {<br>            if (!event.active) simulation.alphaTarget(0.3).restart();<br>            d.fx = d.x;<br>            d.fy = d.y;<br>          })<br>          .on(&quot;drag&quot;, (event, d) =&gt; {<br>            d.fx = event.x;<br>            d.fy = event.y;<br>          })<br>          .on(&quot;end&quot;, (event, d) =&gt; {<br>            if (!event.active) simulation.alphaTarget(0);<br>            d.fx = null;<br>            d.fy = null;<br>          })<br>      );<br><br> // draws labels (node names) next to each circle.<br>    const label = g<br>      .append(&quot;g&quot;)<br>      .selectAll(&quot;text&quot;)<br>      .data(nodes)<br>      .join(&quot;text&quot;)<br>      .text((d) =&gt; d.id)<br>      .attr(&quot;font-size&quot;, 10)<br>      .attr(&quot;dx&quot;, 12)<br>      .attr(&quot;dy&quot;, &quot;.35em&quot;);<br><br>// every time the simulation updates (referred to as a &quot;tick&quot;), we recalculate <br>// and redraw the positions of the nodes, links, and labels so they animate <br>// smoothly.<br>    simulation.on(&quot;tick&quot;, () =&gt; {<br>      link<br>        .attr(&quot;x1&quot;, (d: any) =&gt; (d.source as any).x)<br>        .attr(&quot;y1&quot;, (d: any) =&gt; (d.source as any).y)<br>        .attr(&quot;x2&quot;, (d: any) =&gt; (d.target as any).x)<br>        .attr(&quot;y2&quot;, (d: any) =&gt; (d.target as any).y);<br><br>      node.attr(&quot;cx&quot;, (d: any) =&gt; d.x).attr(&quot;cy&quot;, (d: any) =&gt; d.y);<br>      label.attr(&quot;x&quot;, (d: any) =&gt; d.x).attr(&quot;y&quot;, (d: any) =&gt; d.y);<br>    });<br><br>// cleanup: stops the simulation when the component unmounts.<br>    return () =&gt; {<br>      simulation.stop();<br>    };<br>  }, [nodes, links]);<br><br>// renders the SVG container.<br>  return (<br>    &lt;svg ref={svgRef} style={{ width: &quot;100%&quot;, height: &quot;100vh&quot; }}&gt;<br>      &lt;g ref={gRef}&gt;&lt;/g&gt;<br>    &lt;/svg&gt;<br>  );<br>};<br><br>export default Diagram;</pre><p>And that’s it! That’s all the code we need to get this application up and running.</p><h4>Running the application</h4><p>Let’s test it out. First, we need a file to upload. In our current setup, this has to be a <strong>zipped Go repository</strong>. So, why don’t we zip <em>this</em> project and see how it works? <em>Inception</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/181/1*QCab_jwWq56lWcjWvMCtPw.png" /><figcaption>goflow folder and zipped goflow file</figcaption></figure><p>After zipping (or compressing) the folder, we’re ready to test out our code.</p><p>Navigate back to the code and, in the terminal, navigate to the backend folder. For example: cd backend</p><p>Once you’re there, type: go run . to start the backend server.</p><p>You’re going to do the same for the frontend. Again, in the terminal, navigate to the frontend folder and type: npm run dev and this will start the frontend application. Open the link in the terminal to see it (e.g. <a href="http://localhost:5173/"><em>http://localhost:5173/</em></a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*zlWuQhdkIJXdvcXV0KSchQ.png" /><figcaption>Running application with zip file uploaded</figcaption></figure><p>For the file, you’re going to choose the one we zipped and then you should see some magic:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*skJS-I9iHPUGwWw7nImnig.png" /><figcaption>Application showing code flow graph</figcaption></figure><p>Cool, right? This graph shows all the functions we have in our code and the functions they call. You can click on a specific function in the graph and <strong>isolate its function flow</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ILKd8YTzCtIBoGtmjfLQaA.png" /><figcaption>Isolated function flow of BuildCodeFlowDiagram function</figcaption></figure><p>And that’s it! I hope you enjoyed this walkthrough. If you did, you can help me make more (if you can!): <a href="https://buymeacoffee.com/statlfc">https://buymeacoffee.com/statlfc</a></p><blockquote><strong>Note</strong>: This application is designed to get you started and is by no means a finished article. Challenge yourself to improve it and add your own features. I’ve started implementing AI into the project to provide short summaries of each function alongside its flow.<strong> I’ll either add the tutorial to this article or as its own article.</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b1ab6588693" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/turning-go-code-into-interactive-diagrams-with-react-and-d3-js-5b1ab6588693">Turning Go Code into Interactive Diagrams with React and D3.js</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Forget Chatbots, build a Statbot!]]></title>
            <link>https://medium.com/rewrite-tech/forget-chatbots-build-a-statbot-0fd9617c5aed?source=rss-9d12aafc9fb1------2</link>
            <guid isPermaLink="false">https://medium.com/p/0fd9617c5aed</guid>
            <category><![CDATA[football]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Sammy-Jo Wymer]]></dc:creator>
            <pubDate>Tue, 10 Dec 2024 16:19:45 GMT</pubDate>
            <atom:updated>2025-07-17T14:00:51.797Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dLWoBUL2xh5XrxucntI3IQ.jpeg" /><figcaption>Photo by Tembela Bohle: <a href="https://www.pexels.com/photo/people-watching-soccer-game-10463646/">https://www.pexels.com/photo/people-watching-soccer-game-10463646/</a></figcaption></figure><p>StatLFC is an AI application built using <a href="https://www.python.org/">Python</a>, <a href="https://streamlit.io/">Streamlit</a>, <a href="https://openai.com/">OpenAI</a> and <a href="https://www.langchain.com/">LangChain</a>. It provides users with information about Liverpool FC’s current 2024/25 season, including recent match results and player statistics.</p><h3>Features of StatLFC</h3><ul><li><strong>Recent match results:</strong> See the latest match scores for LFC.</li><li><strong>Player stats:</strong> Ask about player statistics such as goals, assists, player minutes, and more.</li><li><strong>Interactive chat:</strong> Use as a normal chatbot and discuss all things LFC.</li><li><strong>Advanced AI features: </strong>Use of LangChain and FAISS for similarity searches, resulting in more efficient response processing.</li></ul><p>This guide will walk you through the steps to build and deploy this app from scratch.</p><h3>Step 1: Set up development environment</h3><h4>Prerequisites</h4><p>To follow this guide, you will need <a href="https://www.python.org/downloads/"><strong>Python</strong></a><strong> </strong>installed (my current version is <strong>3.12.0</strong>). A basic knowledge of Python will also be helpful but it’s not vital.</p><h4>Install Required Packages</h4><p>Open your IDE (I’m using<strong> </strong><a href="https://code.visualstudio.com/"><strong>VS code</strong></a>). Open the terminal and run the following command to install all necessary packages:</p><pre>pip install streamlit beautifulsoup4 langchain openai faiss-cpu</pre><ul><li><strong>Streamlit</strong>: This will allow us to build a quick frontend for our app.</li><li><strong>BeautifulSoup4</strong>: To get the relevant LFC data from <a href="https://fbref.com/en/squads/822bd0ba/Liverpool-Stats">fbref</a>.</li><li><strong>LangChain</strong>: To break down this data into smaller chunks for efficient processing.</li><li><strong>OpenAI</strong>: To communicate with OpenAI&#39;s GPT model to process prompts and generate responses to user questions.</li><li><strong>FAISS</strong>: Stores embeddings of the data chunks for efficient similarity searches. This allows us to retrieve the most relevant data chunks based on their similarity to the user’s question.</li></ul><h3>Step 2: Create initial application</h3><ol><li>Create a main.py file in the root directory of your project. This file will serve as the <strong>main entry point</strong> for your app.</li><li>Open main.py and <strong>import the packages you </strong>installed in Step 1<strong> </strong>(<em>see code example below</em>).</li><li><strong>Configure the Streamlit page</strong> with a title, icon, and layout settings.</li><li>Use a markdown block to <strong>apply CSS styling</strong> (<em>we’re using Liverpool colours of course!</em>)</li><li>Add a<strong> simple title </strong>within a container (<em>we will add more here later)</em>.</li></ol><pre># main.py<br><br># Step 2.2<br>import streamlit as st<br>from scraper_functions import get_result_info<br><br># Step 2.3<br>st.set_page_config(page_title=&quot;StatLFC&quot;, page_icon=&quot;⚽&quot;, layout=&quot;centered&quot;)<br><br># Step 2.4<br>primary_color = &quot;#A50034&quot;  # Liverpool Red<br>secondary_color = &quot;#FFFFFF&quot;  # White<br>background_color = &quot;#F3F3F3&quot;  # Light Gray<br>card_color = &quot;#FFDDC1&quot;  # Soft Orange for card background<br><br>st.markdown(<br>    f&quot;&quot;&quot;<br>    &lt;style&gt;<br>    body {{<br>        background-color: {background_color};<br>    }}<br>    .container {{<br>        padding: 1.25rem;<br>        border-radius: 15px;<br>        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);<br>        background-color: {card_color};<br>    }}<br>    .title {{<br>        font-size: 3.125rem;<br>        color: {primary_color};<br>        text-align: center;<br>        text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.3);<br>    }}<br>    .match-result {{<br>        background-color: {secondary_color};<br>        border-radius: 5px;<br>        padding: 0.625rem;<br>        margin: 0.313rem;<br>        box-shadow: 0px 1px 5px rgba(0, 0, 0, 0.2);<br>        color: black;<br>    }}<br>    .upcoming-match {{<br>        background-color: {primary_color};<br>        color: {secondary_color};<br>        border-radius: 5px;<br>        padding: 0.625rem;<br>        margin-bottom: 1.25rem;<br>        box-shadow: 0px 1px 5px rgba(0, 0, 0, 0.2);     <br>    }}<br>    .header {{<br>        color: {primary_color};<br>        text-align: center;<br>    }}<br>    .response {{<br>        background-color: {background_color};<br>        color: black;<br>        padding: 0.625rem;<br>        border-radius: 5px;<br>        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);<br>    }}<br>    &lt;/style&gt;<br>    &quot;&quot;&quot;,<br>    unsafe_allow_html=True<br>)<br><br># Step 2.5<br>with st.container():<br>        st.markdown(&#39;&lt;h1 class=&quot;title&quot;&gt;StatLFC&lt;/h1&gt;&#39;, unsafe_allow_html=True)</pre><h3>Step 3: Create helper functions</h3><h4>scraper_functions.py</h4><ol><li>Create a new file called scraper_functions.py. In this file, we will create a function which <strong>gets data about Liverpool’s players and match statistics</strong> from <a href="https://fbref.com/en/squads/822bd0ba/Liverpool-Stats">fbref</a>.</li><li>Import required libraries:</li></ol><pre># scraper_functions.py<br><br>import requests from bs4 <br>import BeautifulSoup</pre><p>3. Define the function to get this data:</p><pre># scraper_functions.py<br><br># scrape the page and store all the page data<br>url = &quot;https://fbref.com/en/squads/822bd0ba/all_comps/Liverpool-Stats-All-Competitions&quot;<br>response = requests.get(url)<br>soup = BeautifulSoup(response.content, &quot;html.parser&quot;)<br><br># this function gets specific match information from the page, e.g. date,<br># competition, opponent, result, etc.<br>def get_result_info():<br>    matches_table = soup.find(&quot;table&quot;, {&quot;id&quot;: &quot;matchlogs_for&quot;})<br><br>    results = []<br>    <br>    for row in matches_table.find(&quot;tbody&quot;).find_all(&quot;tr&quot;):<br>        cols = row.find_all(&quot;td&quot;)<br>        <br>        if len(cols) &gt; 0:<br>        <br>            date = row.find(&#39;th&#39;, {&#39;data-stat&#39;: &#39;date&#39;}).text.strip()<br>            competition = row.find(&#39;td&#39;, {&#39;data-stat&#39;: &#39;comp&#39;}).text.strip()<br>            matchweek = row.find(&#39;td&#39;, {&#39;data-stat&#39;: &#39;round&#39;}).text.strip()<br>            home_or_away = row.find(&#39;td&#39;, {&#39;data-stat&#39;: &#39;venue&#39;}).text.strip()<br>            opponent = row.find(&#39;td&#39;, {&#39;data-stat&#39;: &#39;opponent&#39;}).text.strip()<br>            opponent = remove_emoji_text(opponent)<br>            result = row.find(&#39;td&#39;, {&#39;data-stat&#39;: &#39;result&#39;}).text.strip()<br> <br>    <br>            results.append({<br>                &quot;date&quot;: date,<br>                &quot;competition&quot;: competition,<br>                &quot;matchweek&quot;: matchweek,<br>                &quot;home_or_away&quot;: home_or_away,<br>                &quot;opponent&quot;: opponent,<br>                &quot;result&quot;: result<br>            })<br>    <br>    return results<br><br># this function is the same as the one above but gets specific player<br># information from the page instead, e.g. player, posiiton, age, etc.<br>def get_player_info():<br>    player_table = soup.find(&quot;table&quot;, {&quot;id&quot;: &quot;stats_standard_combined&quot;})<br><br>    players = []<br><br>    for row in player_table.find(&quot;tbody&quot;).find_all(&quot;tr&quot;):<br>        cols = row.find_all(&quot;td&quot;)<br><br>        if len(cols) &gt; 0:<br><br>            player = row.find(&#39;th&#39;, {&#39;data-stat&#39;: &#39;player&#39;}).text.strip()<br>            position = row.find(&#39;td&#39;, {&#39;data-stat&#39;: &#39;position&#39;}).text.strip()<br>            age = row.find(&#39;td&#39;, {&#39;data-stat&#39;: &#39;age&#39;}).text.strip()<br>            goals = row.find(&#39;td&#39;, {&#39;data-stat&#39;: &#39;goals&#39;}).text.strip()<br><br>            players.append({<br>                &quot;player&quot;: player,<br>                &quot;position&quot;: position,<br>                &quot;age&quot;: age,<br>                &quot;goals&quot;: goals,<br><br>            })<br><br>    <br>    return players<br><br># this is a helper function which removes the nationality flag emoji from <br># the text<br>def remove_emoji_text(opponent_name):<br>    text = opponent_name.split()<br>    <br>    if text and text[0].islower():<br>        text.pop(0)<br>    <br>    return &#39; &#39;.join(text)      <br></pre><h4>langchain_helper.py</h4><ol><li>Create a langchain_helper.py file<strong> </strong>to handle AI-related queries.</li><li>Import required libraries:</li></ol><pre># langchain_helper.py<br><br>from datetime import datetime<br>from langchain_text_splitters import RecursiveCharacterTextSplitter<br>import streamlit as st<br>from langchain_openai import OpenAI<br>from langchain_core.prompts import PromptTemplate<br>from langchain.chains import LLMChain<br>from langchain_openai import OpenAIEmbeddings<br>from scraper_functions import get_result_info, get_player_info, get_goalkeeper_info<br>from langchain.docstore.document import Document<br>from langchain_community.vectorstores import FAISS</pre><p>3. Create a function to get specific data from scraped data:</p><pre># langchain_helper.py<br><br>def create_documents_from_scraped_data():<br>    match_results = get_result_info()<br>    player_stats = get_player_info()<br><br>    match_docs = [<br>        f&quot;{match[&#39;date&#39;]} - vs {match[&#39;opponent&#39;]}: {match[&#39;result&#39;]}, &quot;<br>        f&quot;Competition: {match[&#39;competition&#39;]}, Matchweek: {match[&#39;matchweek&#39;]}, playing {match[&#39;home_or_away&#39;]}, &quot;<br> <br>        for match in match_results<br>    ]<br><br><br>    player_docs = [<br>        f&quot;Player: {player[&#39;player&#39;]}, Position: {player[&#39;position&#39;]}, &quot;<br>        f&quot;Age: {player[&#39;age&#39;]}, &quot;<br>        f&quot;Goals: {player[&#39;goals&#39;]}, &quot;<br><br>        for player in player_stats<br>    ]<br><br><br>    docs = match_docs + player_docs<br>    return docs</pre><p>3. Create a vector database:</p><pre># langchain_helper.py<br><br># This code creates a searchable database of information from the data we<br># scraped and selected. It first breaks the text into smaller, manageable <br># pieces, then converts these pieces into numerical formats (called embeddings)<br># These embeddings are stored in a specialised database (FAISS) that makes it <br># easy to find and retrieve relevant information quickly based on user questions.<br><br>def create_vector_db(docs: str)-&gt; FAISS:<br># NOTE: we will add this OPENAI_API_KEY at the end<br>    api_key = st.secrets[&quot;OPENAI_API_KEY&quot;]<br>    embeddings = OpenAIEmbeddings(openai_api_key=api_key)<br>    text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)<br>    documents = [Document(page_content=doc) for doc in docs]<br>    docs = text_splitter.split_documents(documents)<br>    vector_store = FAISS.from_documents(docs, embeddings)<br><br>    return vector_store</pre><p>4. Create a function to embed the selected data:</p><blockquote>Before we dive into this function code, it’s good to know why we’re embedding the data in the first place. Instead of just matching exact words, embeddings let us capture the underlying meaning of text. For example, “<em>How many goals did Liverpool score?”</em> and <em>“Liverpool’s goal count?”</em> would be recognised as similar, even though they don’t use the exact same words.</blockquote><blockquote>This means users don’t need to phrase their queries in specific ways to get good answers. They can ask questions naturally, and our bot will still understand and find relevant information.</blockquote><pre># lanchain_helper.py<br><br># this function takes a user question, compares it to the data we<br># scraped and selected, and uses embeddings to find the most relevant information<br># to answer the query (as described above). <br><br>def get_response_from_query_with_embeddings(db, query, k=4):<br>    docs = db.similarity_search(query, k=k) <br>    docs_str = &quot; &quot;.join([doc.page_content for doc in docs])<br>    today = datetime.today().date()<br>    llm = OpenAI(model=&quot;gpt-3.5-turbo-instruct&quot;, temperature=0, max_tokens=100)<br><br>    prompt = PromptTemplate(<br>        input_variables=[&quot;query&quot;, &quot;docs&quot;, &quot;today&quot;], <br>        template=&quot;&quot;&quot;<br>        You are a helpful assistant who can answer questions about Liverpool FC&#39;s current 2024/25 season.<br>        Answer the user&#39;s question: {query} using this information: {docs}. <br>        Don&#39;t make anything up and only answer the question you are asked. Don&#39;t provide additional information.<br>        Keep your answers as short as possible and be polite.<br>        &quot;&quot;&quot;<br>    )<br><br>    chain = LLMChain(llm=llm, prompt=prompt)<br><br>    response = chain.run(query=query, docs=docs_str, today=today)<br>    response = response.replace(&quot;\n&quot;, &quot;&quot;)<br><br>    return response</pre><h3>Step 4: Display recent match results</h3><p>Now that we have all of the functions we need for organising the LFC data we want to use, we can start to shape our frontend for user interaction. The first thing we will do is add a section which shows recent match result and the next upcoming fixture.</p><ol><li>Add datetime import:</li></ol><pre># main.py <br><br>import streamlit as st<br>from scraper_functions import get_result_info<br>from datetime import datetime</pre><p>2. Create a function to format the scraped dates:</p><pre># main.py<br><br># this function takes the date data we receive from the scraped data<br># and formats it in a more readable way for the user.<br><br>def format_match_dates(date):<br>    formatted_date = datetime.strptime(date, &#39;%Y-%m-%d&#39;).strftime(&#39;%d %B %Y&#39;)<br>    return formatted_date<br><br># get today&#39;s date<br>today = datetime.today().date()<br></pre><p>3. Get recent results and upcoming matches:</p><pre># main.py<br><br># get the match result info using the function we created in &#39;scraper_functions&#39;<br>match_results = get_result_info()<br><br># this line creates a list of past matches by filtering &#39;match_results&#39;. <br># It includes only those matches where the match date is less than or equal to<br># today&#39;s date. The date is parsed from a string format (&#39;%Y-%m-%d&#39;) to a <br># datetime object.<br>past_matches = [match for match in match_results if datetime.strptime(match[&#39;date&#39;], &#39;%Y-%m-%d&#39;).date() &lt;= today]<br><br># we have to reverse the list so that the results appear in the correct order<br># on the page.<br>past_matches = past_matches[::-1]<br><br># this line does the same as &#39;past_matches&#39;, except it includes only those <br># matches where the match date is greater than today&#39;s date. <br>upcoming_matches = [match for match in match_results if datetime.strptime(match[&#39;date&#39;], &#39;%Y-%m-%d&#39;).date() &gt; today]<br></pre><p>4. Display past and upcoming matches</p><p>Now, below the header we created at the beginning (StatLFC), we’re going to add the recent and upcoming match information:</p><pre># main.py<br><br># ... previous code<br><br>    st.markdown(&#39;&lt;h1 class=&quot;title&quot;&gt;StatLFC&lt;/h1&gt;&#39;, unsafe_allow_html=True)<br># add the following code below the header we added at the beginning.<br><br># Add a subtitle for recent results<br>    st.header(&quot;Recent Results:&quot;)<br><br># show only the last 3 match result and format the date.<br>    for match in past_matches[:3]: <br>            date = format_match_dates(match[&#39;date&#39;])<br>            st.markdown(f&#39;&lt;div class=&quot;match-result&quot;&gt;{date} - {match[&quot;home_or_away&quot;]} vs {match[&quot;opponent&quot;]}: {match[&quot;goals_for&quot;]} - {match[&quot;goals_against&quot;]}  ({match[&quot;result&quot;]})&lt;/div&gt;&#39;, unsafe_allow_html=True)<br><br># Add another subtitle for the upcoming match<br>        st.header(&quot;Upcoming match:&quot;)<br><br># show only the next upcoming game and format the date.<br>        for match in upcoming_matches[:1]: <br>            date = format_match_dates(match[&#39;date&#39;])<br>            st.markdown(f&#39;&lt;div class=&quot;upcoming-match&quot;&gt;{date} - {match[&quot;home_or_away&quot;]} vs {match[&quot;opponent&quot;]}&lt;/div&gt;&#39;, unsafe_allow_html=True)</pre><p>You can run your app with this command:</p><pre>streamlit run main.py</pre><p>…and it should look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YOIt1SfrNkvzh9bPhRlQEQ.png" /><figcaption>StatLFC page showing three recent match result and one upcoming game</figcaption></figure><blockquote>Do you see a bug we have here? The result against Real Madrid says <strong>None — None ()</strong>. This is because the game is actually today (while I’m writing this article)! There’s an optional step at the end of the article to fix this.</blockquote><h3>Step 5: Allow user input and display bot response</h3><p>Directly below the match information we displayed in Step 4, we will now add a user input field so the user can ask questions, as well as a response area to display the bot’s answers.</p><ol><li>Add imports:</li></ol><pre># main.py <br><br>from datetime import datetime<br>from langchain_text_splitters import RecursiveCharacterTextSplitter<br>import streamlit as st<br>from langchain_openai import OpenAI<br>from langchain_core.prompts import PromptTemplate<br>from langchain.chains import LLMChain<br>from langchain_openai import OpenAIEmbeddings<br>from scraper_functions import get_result_info, get_player_info, get_goalkeeper_info<br>from langchain.docstore.document import Document<br>from langchain_community.vectorstores import FAISS</pre><p>2. Add user input and response area:</p><pre># main.py<br><br># ...previous code<br><br># Add a text input field using streamlit, and add some text above it.<br> query = st.text_input(&quot;Alright laa! Ask about recent Liverpool results or player stats:&quot;, max_chars=100)<br><br># create the documents using the function we created in &#39;langchain_helper&#39;<br>        docs = lch.create_documents_from_scraped_data()<br><br># if there is a user question and documents are available, create the vector db<br># using the docs, then use this to return a response to the user&#39;s question.<br>        if query and docs:<br>            db = lch.create_vector_db(docs)<br>            response = lch.get_response_from_query_with_embeddings(db, query)<br><br># create a subheading for the response<br>            st.subheader(&quot;Response:&quot;)<br><br># create a text area using streamlit to display the response<br>            st.markdown(f&#39;&lt;div class=&quot;response&quot;&gt;{textwrap.fill(response, width=80)}&lt;/div&gt;&#39;, unsafe_allow_html=True)</pre><p>Finally, at the very bottom of the page, let’s acknowledge the resources that allow us to create such a project:</p><pre># main.py<br><br>st.markdown(&quot;&lt;p style=&#39;text-align: center; padding-top: 20px;&#39;&gt;Data provided by FBref.com and OpenAI&#39;s GPT-3.5-turbo-instruct model.&lt;/p&gt;&quot;, unsafe_allow_html=True)</pre><p>Now, if you refresh the page, it should look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nz4HITfMXEMxPtpLZyFsdw.png" /><figcaption>StatLFC page now showing user input field</figcaption></figure><p>Nice! We’re almost ready to use it. All we need to do now is add our <a href="https://help.openai.com/en/articles/4936850-where-do-i-find-my-openai-api-key">OpenAI API key</a> and then we’re ready to go!</p><h3>Step 6: Secure API key in secrets.toml</h3><ol><li>In the root of your project, create a .streamlit/secrets.toml file to store your OpenAI API key securely:</li></ol><pre># .streamlit/secrets.toml<br><br>OPENAI_API_KEY = &quot;your_openai_api_key&quot;</pre><h3>Step 7: Run and test app locally</h3><p>If you haven’t already, you can run the app to see it in action:</p><pre>streamlit run main.py</pre><p>This will open your app at http://localhost:8501, where you can view match details and interact with the chatbot.</p><p>Let’s try it out then…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*laBE-LvLRPB7VHrNxDzY5Q.png" /><figcaption>StatLFC answering the question “who is our top scorer?” with the answer “The top scorer for Liverpool FC this season is Mohamed Salah with a total of 12 goals.”</figcaption></figure><blockquote><em>Mo Salah, Mo Salah, Mo Salah runnin’ down the wiiiing, Salaahhhhh…</em></blockquote><p>I hope you enjoyed this article and please let me know if you have any questions! You can <strong>find the full code on </strong><a href="https://github.com/swymerjo/chatlfc"><strong>GitHub</strong></a><strong> </strong>and the <a href="https://chatlfc.streamlit.app/"><strong>deployed app hosted on Streamlit</strong></a>, but bear in mind that I’m updating it regularly. YNWA!</p><h3>Optional: Step 8: Deploy app</h3><ol><li>Add a requirements.txt file to the root of your project and add the following packages:</li></ol><pre>streamlit<br>python-dotenv<br>langchain<br>datetime<br>bs4<br>langchain_openai<br>langchain-community<br>faiss-cpu</pre><p>2. <strong>Push</strong> your app to your <strong>GitHub repository</strong>.</p><p>3.<strong> Deploy to </strong><a href="https://streamlit.io/"><strong>Streamlit</strong></a><strong> Cloud </strong>or another platform of your choice by linking your GitHub repository. Remember to add your OPENAI_API_KEY to the environment variables of whichever platform you deploy with.</p><p>And that’s it!</p><h3>Optional: Step 9: Fix bug</h3><p>As we saw earlier, we had a bug in our code which meant that games which hadn’t been played yet (on the day of the game) would be shown in the recent results section.</p><p>We can fix this by scraping one more piece of data from fbref.com:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*1QvT6HlcD8IXZw7-Nn1_5w.png" /><figcaption>A page on fbref.com which shows the start times of Liverpool matches</figcaption></figure><p>When we open developer tools and inspect the time element(s), we see that we can target this element with start-time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*Tv8VFzeI22IpLJJGGPShpQ.png" /><figcaption>The data-stat name we can target is called start_time</figcaption></figure><p>So, let’s go ahead and add this to our get_results_info() function:</p><pre># scraper_functions.py<br><br># ...previous code<br><br># newly added code<br>  start_time = row.find(&#39;td&#39;, {&#39;data-stat&#39;: &#39;start_time&#39;}).text.strip()<br><br><br># .. other code<br><br><br>  results.append({<br>     &quot;date&quot;: date,<br># newly added code<br>     &quot;start_time&quot;: start_time,</pre><p>Now that we have this information, let’s use it in our main.py:</p><pre># main.py<br><br># get the current time<br>now = datetime.now()<br><br># update how we get today&#39;s date<br>today = now.date()<br><br># update &#39;patch_matches&#39; so it compares current time instead of current date<br>past_matches = [<br>    match for match in match_results<br>    if datetime.strptime(f&quot;{match[&#39;date&#39;]} {match[&#39;start_time&#39;]}&quot;, &#39;%Y-%m-%d %H:%M&#39;) &lt;= now<br>]<br>past_matches = past_matches[::-1]<br><br># update &#39;upcoming_matches&#39; in the same way<br>upcoming_matches = [match for match in match_results if datetime.strptime(f&quot;{match[&#39;date&#39;]} {match[&#39;start_time&#39;]}&quot;, &#39;%Y-%m-%d %H:%M&#39;) &gt; now]</pre><p>And now when we reload our page, we can see that the bug is fixed. Worth the extra effort, right? :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*X3h7IxauIahHvgKrlEn4rQ.png" /><figcaption>StatLFC showing correct recent and upcoming matches</figcaption></figure><p>If you enjoyed this resource, you can help me make more (if you can!): <a href="https://buymeacoffee.com/statlfc">https://buymeacoffee.com/statlfc</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0fd9617c5aed" width="1" height="1" alt=""><hr><p><a href="https://medium.com/rewrite-tech/forget-chatbots-build-a-statbot-0fd9617c5aed">Forget Chatbots, build a Statbot!</a> was originally published in <a href="https://medium.com/rewrite-tech">REWRITE TECH by Diconium</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Multilingual Teams Bots: Adding Adaptive Cards with Dynamic Language Support]]></title>
            <link>https://medium.com/rewrite-tech/building-multilingual-teams-bots-adding-adaptive-cards-with-dynamic-language-support-8772ce73a5aa?source=rss-9d12aafc9fb1------2</link>
            <guid isPermaLink="false">https://medium.com/p/8772ce73a5aa</guid>
            <category><![CDATA[design]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[microsoft-teams]]></category>
            <dc:creator><![CDATA[Sammy-Jo Wymer]]></dc:creator>
            <pubDate>Fri, 13 Sep 2024 09:02:38 GMT</pubDate>
            <atom:updated>2025-07-17T14:01:06.085Z</atom:updated>
            <content:encoded><![CDATA[<p>When building bots for Microsoft Teams, using <a href="https://learn.microsoft.com/en-us/adaptive-cards/"><strong>Adaptive Cards</strong></a> provides a <strong>visually engaging way to present content</strong>.</p><p>For example, instead of a simple bot message:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*uJNmxdbX96N3GRQ-aMDNmw.png" /><figcaption>Teams bot message</figcaption></figure><p>You can impress your user with a more entertaining adaptive card:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*8dxJR5XN676yGEGqQpvsmQ.png" /><figcaption>Simple adaptive card in Teams</figcaption></figure><p>Even better… what if you could detect the user’s locale and dynamically change the greeting language based on this?</p><p>In this article, I’ll walk you through how to create dynamic adaptive cards in a Teams bot using TypeScript.</p><h3>What are Adaptive Cards?</h3><p>An <strong>adaptive card</strong> is basically a configurable card that you can add to your Microsoft Teams application. As highlighted above, these cards are designed to make messages <strong>look better </strong>and more <strong>interactive</strong>. Instead of being limited to sending plain text chat messages, you can add features such as <strong>images, buttons</strong>, and <strong>formatted text</strong>.</p><h3>Pre-requisites</h3><ul><li>A working Microsoft Teams bot — read my <a href="https://medium.com/rewrite-tech/creating-a-teams-copilot-bot-in-azure-0082ea9ae439">last article</a> to see how you can easily set yours up.</li></ul><h3>Table of Contents</h3><ol><li><a href="#32ac">Setting up Localisation in Teams Bot</a></li><li><a href="#8ad1">Creating an Adaptive Card with Translations</a></li><li><a href="#b38d">Displaying the Adaptive Card in Teams</a></li><li><a href="#6e66">Complete Code Example</a></li><li><a href="#4ed1">Testing in Microsoft Teams</a></li><li><a href="#3c8a">Additional configuration (extra)</a></li></ol><h3>1. Setting up Localisation in Teams Bot</h3><p>To handle text translations, we will use <a href="https://www.i18next.com/"><strong>i18next</strong></a>.</p><p>So, let’s jump right in! Open up your bot code in <a href="https://code.visualstudio.com/">VS code</a>.</p><h4>Install i18next</h4><p>If you don’t have <strong>i18next</strong> installed already, you can do so by running the following command in your terminal:</p><pre>npm install i18next</pre><p>Create your <strong>translations files</strong> for different languages. Here is a sample structure for English and Spanish translations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*Lla8E0lmFHVb4KXHNYnq_g.png" /><figcaption>Translations folder structure</figcaption></figure><p>Each translation.json file contains key-value pairs for translated text. <br>For example, in src/locales/en/translation.json:</p><pre>{<br>  &quot;chat&quot;: {<br>    &quot;greeting_text&quot;: &quot;Welcome to the bot!&quot;,<br>    &quot;greeting_text_help&quot;: &quot;How can I assist you today?&quot;,<br>  }<br>}</pre><p>In src/locales/es/translation.json:</p><pre>{<br>  &quot;chat&quot;: {<br>    &quot;greeting_text&quot;: &quot;¡Bienvenido al bot!&quot;,<br>    &quot;greeting_text_help&quot;: &quot;¿Cómo puedo ayudarte hoy?&quot;,<br>  }<br>}</pre><p>Create a file in the src folder called i18n.ts and add the following code:</p><pre>// src/i18n.ts<br><br>import i18n from &quot;i18next&quot;;<br>import en from &quot;./locales/en/translation.json&quot;;<br>import es from &quot;./locales/es/translation.json&quot;;<br><br>i18n.init({<br>  resources: {<br>    en,<br>    es,<br>  },<br>  lng: &quot;en&quot;,<br>  fallbackLng: &quot;en&quot;,<br>  interpolation: {<br>    escapeValue: false,<br>  },<br>});<br>export default i18n;</pre><p>This code initialises the <strong>i18n</strong> library with the English (en) and Spanish (es) translation files that we just created. It sets English as the default language (lng) and fallback language if no other locale is detected.</p><h3>2. Creating an Adaptive Card with Translations</h3><p>Now, let’s get to the fun stuff and create the adaptive card. Add the following function to your main bot file (<em>mine is</em> app.ts) and we’ll dive into what it means.</p><pre>// src/app.ts<br><br>// ...previous bot code<br><br> function createGreetingCard(locale: string) {<br>  return {<br>    $schema: &quot;https://adaptivecards.io/schemas/adaptive-card.json&quot;,<br>    type: &quot;AdaptiveCard&quot;,<br>    version: &quot;1.0&quot;,<br>    body: [<br>      {<br>        type: &quot;Image&quot;,<br>        url: &quot;https://github.com/wymersam/dicogptimage/blob/main/dicoGPT.png?raw=true&quot;,<br>        height: &quot;150px&quot;,<br>      },<br>      {<br>        type: &quot;TextBlock&quot;,<br>        text: i18n.t(&quot;chat.greeting_text&quot;, { lng: locale }),<br>        wrap: true,<br>        color: &quot;accent&quot;,<br>      },<br>      {<br>        type: &quot;TextBlock&quot;,<br>        text: i18n.t(&quot;chat.greeting_text_help&quot;, { lng: locale }),<br>        color: &quot;warning&quot;,<br>      },<br>    ],<br>  };<br>}<br><br>// ...end of file</pre><h4>Code Explanation:</h4><p>This is the code that <strong>creates an adaptive card</strong> with <strong>dynamic translation</strong> possibilities.</p><ul><li><strong>Structure</strong>: Adaptive cards are created via a JSON object, which makes them really easy to configure. In our super simple example, we include an <strong>image</strong> (<em>note that this has to be a URL</em>) and <strong>two blocks of text</strong> which come from the translation files we created in the previous step. We’ll add some more styling in the next steps.</li><li><strong>i18n.t</strong>: This method retrieves the translated text based on the <strong><em>locale </em></strong><em>(e.g. en-US</em>)<strong> </strong>passed. As you can see, we pass the locale as an argument to this function to determine which language will be shown. But where do we get this locale value from?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*8dxJR5XN676yGEGqQpvsmQ.png" /><figcaption>Simple adaptive card in Teams</figcaption></figure><h3>3. Displaying the Adaptive Card in Teams</h3><p>Once you have the function to create the adaptive card, you then need to create another function to <strong>display the card with the correct translation</strong> in the Teams chat:</p><pre>// src/app.ts<br><br>async function showGreetingCard(context: TurnContext, locale: string) {<br><br>// Show the adaptive card in the chat<br>  await context.sendActivity({<br>    attachments: [CardFactory.adaptiveCard(createGreetingCard(locale))],<br>  });<br>}</pre><h4>Code Explanation:</h4><ul><li><strong>context.locale</strong>: This is where we find out the locale of the user.</li><li><strong>defaultLanguage</strong>: In case no locale is detected, a fallback locale is used (<em>e.g. en-US for English</em>).</li><li><strong>CardFactory.adaptiveCard()</strong>: This method allows us to use the JSON object we created in the createGreetingCard function to <strong>style our adaptive card</strong>.</li></ul><h3>4. Complete Code Example</h3><p>Here’s the complete code block for reference, including the event handler (onInstallationUpdate()) for when the bot is installed:</p><pre>// src/app.ts<br><br>import { CardFactory, TurnContext } from &#39;botbuilder&#39;;<br>import i18n from &#39;i18next&#39;;<br><br>// ...other code and imports<br><br>// Set a default locale as a fallback value<br>const defaultLanguage = &quot;en-US&quot;;<br><br>// Show the adaptive card when the bot is installed/updated<br>// This event handler comes from the bot-builder package<br>this.onInstallationUpdate(async (context: TurnContext, next) =&gt; {<br>  <br>  const { locale } = context.activity;<br><br>  await showGreetingCard(context, locale ? locale : defaultLanguage);<br>  <br>  await next();<br>});<br><br>// ...main bot code<br><br><br>function createGreetingCard(locale: string) {<br>  return {<br>    $schema: &quot;https://adaptivecards.io/schemas/adaptive-card.json&quot;,<br>    type: &quot;AdaptiveCard&quot;,<br>    version: &quot;1.0&quot;,<br>    body: [<br>      {<br>        type: &quot;Image&quot;,<br>        url: &quot;https://github.com/wymersam/dicogptimage/blob/main/dicoGPT.png?raw=true&quot;,<br>        height: &quot;150px&quot;,<br>      },<br><br>      {<br>        type: &quot;TextBlock&quot;,<br>        text: &quot;Welcome to the bot!&quot;,<br>        wrap: true,<br>        color: &quot;accent&quot;,<br>      },<br>      {<br>        type: &quot;TextBlock&quot;,<br>        text: &quot;How can I assist you today?&quot;,<br>        wrap: true,<br>        color: &quot;warning&quot;,<br>      },<br>    ],<br>  };<br>}<br><br><br>async function showGreetingCard(context: TurnContext, locale: string) {<br><br>  await context.sendActivity({<br>    attachments: [CardFactory.adaptiveCard(createGreetingCard(locale))],<br>  });<br>}<br><br>// end of code</pre><h3>5. Testing in Microsoft Teams</h3><p>Once you’ve added this functionality to your bot, <strong>redeploy it to Azure</strong> and test it in your Microsoft Teams environment (<em>if needed, you can refer to my </em><a href="https://medium.com/rewrite-tech/creating-a-teams-copilot-bot-in-azure-0082ea9ae439"><em>previous article</em></a><em> on how to do this</em>).</p><ol><li><strong>Install the Bot in a Team</strong>: After installing the bot on Teams, it should send the greeting card in the language based on your Teams locale settings. <br><strong><em>Note</em></strong><em>: The text will only be translated if you have the appropriate </em><em>translation.json file for the user’s locale/language. For example, if your locale is de-DE but you don’t have a translation file for German, then the language will fallback to English.</em></li><li><strong>Change Teams Locale</strong>: Go to Teams settings and change the language (<em>e.g. from English to Spanish</em>). Reinstall or update the bot, and you should see the greeting card now appears in Spanish!</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aJQIx-xPvlEd6ZcuGAFEHw.png" /><figcaption>Adaptive card translation</figcaption></figure><h3>6. Additional Configuration</h3><p>You can configure your adaptive cards even more with features such as <strong>columns, buttons, colours, spacing,</strong> and more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s5G05XYFYUPK2649x8cqNQ.png" /><figcaption>Adaptive card with additional configuration</figcaption></figure><p>In this example, I updated the adaptive card JSON object to have columns, gave the columns a colour, and also added a button which would take the user to the URL provided:</p><pre>// src/app.ts<br><br>function createGreetingCard() {<br>  return {<br>    $schema: &quot;https://adaptivecards.io/schemas/adaptive-card.json&quot;,<br>    type: &quot;AdaptiveCard&quot;,<br>    version: &quot;1.0&quot;,<br>    body: [<br>      {<br>        type: &quot;ColumnSet&quot;,<br>        style: &quot;accent&quot;,<br>        bleed: true,<br>        columns: [<br>          {<br>            type: &quot;Column&quot;,<br>            items: [<br>              {<br>                type: &quot;Image&quot;,<br>                url: &quot;https://github.com/wymersam/dicogptimage/blob/main/dicoGPT.png?raw=true&quot;,<br>                height: &quot;150px&quot;,<br>              },<br>            ],<br>            width: &quot;auto&quot;,<br>          },<br>          {<br>            type: &quot;Column&quot;,<br>            style: &quot;warning&quot;,<br>            bleed: true,<br>            items: [<br>              {<br>                type: &quot;TextBlock&quot;,<br>                text: &quot;Welcome to the bot!&quot;,<br>                wrap: true,<br>              },<br>              {<br>                type: &quot;TextBlock&quot;,<br>                text: &quot;How can I assist you today?&quot;,<br>              },<br>              {<br>                type: &quot;ActionSet&quot;,<br>                actions: [<br>                  {<br>                    type: &quot;Action.Submit&quot;,<br>                    title: &quot;Click Me&quot;,<br>                    url: &quot;www.example.com&quot;,<br>                  },<br>                ],<br>              },<br>            ],<br>            width: &quot;stretch&quot;,<br>          },<br>        ],<br>      },<br>    ],<br>  };<br>}</pre><h4>Conclusion</h4><p>In this guide, we covered how to <strong>create an adaptive card in Microsoft Teams</strong> that <strong>updates the text language dynamically</strong> based on the user’s locale. By using <strong>i18next</strong> and the Microsoft Bot Framework, you can create dynamic, user-friendly bots that support multiple languages.</p><blockquote>Thanks for reading! Why not jump right in and start designing an adaptive card that fits your bot’s requirement?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GP6NuO1rKFT6Gs2G7zBMCQ.png" /></figure><p>If you enjoyed this resource, you can help me make more (if you can!): <a href="https://buymeacoffee.com/statlfc">https://buymeacoffee.com/statlfc</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8772ce73a5aa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/rewrite-tech/building-multilingual-teams-bots-adding-adaptive-cards-with-dynamic-language-support-8772ce73a5aa">Building Multilingual Teams Bots: Adding Adaptive Cards with Dynamic Language Support</a> was originally published in <a href="https://medium.com/rewrite-tech">REWRITE TECH by Diconium</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 Teams copilot bot in Azure]]></title>
            <link>https://medium.com/rewrite-tech/creating-a-teams-copilot-bot-in-azure-0082ea9ae439?source=rss-9d12aafc9fb1------2</link>
            <guid isPermaLink="false">https://medium.com/p/0082ea9ae439</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[bots]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Sammy-Jo Wymer]]></dc:creator>
            <pubDate>Thu, 18 Jul 2024 08:04:49 GMT</pubDate>
            <atom:updated>2025-07-17T14:01:27.937Z</atom:updated>
            <content:encoded><![CDATA[<p>Everyone is building chatbots these days but this article goes to the next level and provides a step-by-step guide on how to <strong>develop</strong>, <strong>deploy</strong>, and <strong>publish</strong> a <em>customised copilot in Teams</em>.</p><p>This article includes:</p><ul><li><strong>Creating Azure resources</strong></li><li><strong>Creating a copilot bot using Teams Toolkit</strong></li><li><strong>Deploying the bot to Azure</strong></li><li><strong>Publishing the bot to Teams</strong></li><li><strong>Customising the bot</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gVxRJHdf0W3umkxNarkYBQ.png" /></figure><h4><em>Prerequisites</em></h4><p>You need a subscription to Azure… <em>but</em> <em>don’t despair! </em>— I signed up for the free trial and that’s all you’ll need for this walkthrough :)</p><h4>Create a resource group in Azure</h4><p>The resource group is the place that will hold all the resources that you create for the bot.</p><ol><li>Once you’re all set up with the subscription, open the <a href="https://portal.azure.com/?quickstart=true#home">Azure portal</a>.</li></ol><p>You should see the Azure services banner:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w5Q1XoVrvRB_fBVo6hqF1A.png" /><figcaption>Azure services banner</figcaption></figure><p>2. Click on <strong>Create a resource</strong>.<br>3. Search for <em>resource group</em> and then select <strong>Create</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*CT9j4i3WJvyMp9wVTFiW6w.png" /><figcaption>Azure marketplace</figcaption></figure><p>4. Select your subscription, choose a name for your resource group, and also select the region you’re based in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*dDFu81hpxV3B7kmGIgjpBQ.png" /><figcaption>Create Azure resource group</figcaption></figure><p>5. Then select<strong> Review + create</strong> (bottom left). And then select <strong>Create</strong>.</p><p>Nice! You’ve successfully created your resource group.</p><h4>Set up an Azure AI service</h4><p>This service allows your bot to use the <em>OpenAI API</em>.</p><ol><li>Back at the <a href="https://portal.azure.com/?quickstart=true#home">Azure portal</a>, select <strong>Create a resource </strong>from the banner and search for<strong> </strong><em>Azure OpenAI</em><strong>.</strong></li><li>Select the following option:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*HZ_hiMDkrPoQR8NQN-lmEQ.png" /><figcaption>Azure OpenAI search service in Azure portal</figcaption></figure><p>3. Click create:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*yEeH_O-wCVqjLfkmqjEigg.png" /><figcaption>Create Azure OpenaI service</figcaption></figure><p><strong><em>Note</em></strong><em>: You may have to </em><a href="https://customervoice.microsoft.com/Pages/ResponsePage.aspx?id=v4j5cvGGr0GRqy180BHbR7en2Ais5pxKtso_Pz4b1_xUNTZBNzRKNlVQSFhZMU9aV09EVzYxWFdORCQlQCN0PWcu"><em>request access to Azure OpenAI service</em></a><em> before you can create this service.</em></p><p>4. Then fill in the fields with your information (note that we are using the resource group that we just created):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*6ErriGJAhVfGcyQHvmBUhw.png" /><figcaption>Create Azure OpenAI service</figcaption></figure><p>5. Once this service has been created (and it may take a while), navigate to this resource.</p><p>While you’re here, click on <strong>Keys and Endpoints</strong> and store the <strong>KEY 1</strong> and <strong>Endpoint</strong> values somewhere handy as you’ll need them when creating your bot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tHt693EwcIqYkYZxAgCNxg.png" /></figure><p><strong><em>Note</em></strong><em>: To find all the resources you’ve created, you can access </em><strong><em>Resource groups</em></strong><em> from the </em><a href="https://portal.azure.com/?quickstart=true#home"><em>Azure portal</em></a><em> and click on the resource group you created in the first step:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*07v8KoG2xvIoF4xc2fX12Q.png" /><figcaption>Azure resource groups</figcaption></figure><p>6. Click on <strong>Go to Azure OpenAI studio</strong> and this will take you to a new page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*_y0FsfqCEFHn9IPL17Vz7A.png" /><figcaption>Azure OpenAI service</figcaption></figure><p>7. Click on <strong>Deployments</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-IY628AlTqqyODnZfzp8yw.png" /><figcaption>Azure OpenAI service portal</figcaption></figure><p>8. Then click <strong>Create new deployment </strong>and fill in the fields. In the following example, I’m using the <em>gpt-4 model</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*Ell8lBNoofFYa7QZYvE8YQ.png" /><figcaption>Create a new deployment</figcaption></figure><p>Again, you should store the <strong>Deployment name </strong>somewhere handy as we’ll be using it when creating our bot.</p><p><strong><em>Note</em></strong><em>: You can see/create more deployment models in the </em><strong>Models</strong><em> section in the Azure OpenAI search portal</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XiibjTldOdwnkXaKGFvQAg.png" /><figcaption>View/create new deployment models</figcaption></figure><p>Well done! You’ve created an <em>Azure OpenAI service</em> that our Teams bot will use to responds to user questions.</p><h4>Create bot</h4><p>To create the bot, you’ll need to ensure you have installed the <a href="https://learn.microsoft.com/en-us/microsoftteams/platform/toolkit/teams-toolkit-fundamentals">Teams Toolkit</a> extension in VS code. Once installed, it should appear in the toolbar like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rcQAHCzzcA8Wnf_tQ-_8Iw.png" /><figcaption>Teams Toolkit in VS code</figcaption></figure><ol><li>Click on the Teams Toolkit icon, then <strong>Create a New App</strong>:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bsrN-Xtn2gwOKIMXt3tYnQ.png" /><figcaption>Create a new Teams Toolkit app</figcaption></figure><p>2. Click on <strong>Custom Copilot</strong> -&gt; <strong>Basic AI Chatbot</strong> -&gt; <strong>TypeScript</strong> -&gt; <strong>Azure OpenAI</strong>.</p><p>3. You’ll then be prompted to add the <strong>key</strong> (KEY 1) that you stored earlier.</p><p>4. You’ll then be prompted to add the <strong>endpoint</strong>.</p><p>5. Then you’ll be prompted to add the <strong>deployment name</strong>.</p><p>6. Choose a <strong>location</strong> on your computer to save the application.</p><p>7. Choose a <strong>name</strong> for your application/bot.</p><p>Once you’ve followed these prompts, VS code will open a new window with your bot code.</p><p>If you navigate to env then env.testtool.user you’ll see the variables you added when creating the bot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jaFo21FSHgrGsm8SK_3cVg.png" /><figcaption>.env file variables</figcaption></figure><p>Congratulations, you’ve created an AI copilot bot!</p><h4>Running the bot</h4><p>In the README.md file, you’ll see instructions for running your newly created bot locally but it’s pretty simple — you just need to click on the <strong>debug<em>/</em>play</strong> button and then <strong>Debug in Test Tool</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_MrpHwnuwuiqcASHo21cCQ.png" /><figcaption>Running the bot locally</figcaption></figure><p>This will open a browser window where you can interact with your bot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dmfdJ1FhTx2oe5ORSKQF3w.png" /><figcaption>Teams Toolkit test tool</figcaption></figure><p>And if you navigate back to your code and check the terminal, you’ll see some additional information about the bot response:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1b1mHX5vWdJm01PlhvBkSA.png" /><figcaption>Bot response information in terminal</figcaption></figure><p>Congratulations! You’re running your bot locally using Teams Toolkit :)</p><h4>Deploying your bot to Azure</h4><ol><li>Open the Teams Toolkit tab in VS code.</li><li>Click on <strong>Provision</strong>:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mdsGeDeF1tdlJwaZOfbdsQ.png" /><figcaption>provision/create the bot resources on Azure</figcaption></figure><p>3. Select your <strong>subscription</strong>.</p><p>4. Then select your <strong>resource group</strong>.</p><p>5. Then click <strong>Provision</strong>.</p><p>6. The provisioning may take a while but once it’s complete a box will appear in the bottom-right corner. Click on <strong>View provisioned resources</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*E2-zpek38JrFXajEpnCxTA.png" /><figcaption>Notification of provisioned resources</figcaption></figure><p>This will open Azure and show you the resources created in your resource group:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vBwGsDXRLRn0VrsuEOhMcw.png" /><figcaption>Azure resources in resource group</figcaption></figure><p><strong><em>Note</em></strong><em>: Your bot resources will have a different name to the ones shown above.</em></p><p>7. The bot will not work until you deploy from Teams Toolkit so navigate back to VS Code, open the Teams Toolkit tab, and below <strong>Provision</strong> you’ll see <strong>Deploy</strong>. Click this and deploy the app to Azure.</p><p>8. Once the deployment has complete (this may also take a bit of time), navigate back to Azure and open the <strong>Azure Bot</strong><em> </em>resource:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YQbDvAbHYsyTZkUqunJJUw.png" /><figcaption>Azure Bot resource</figcaption></figure><p>9. From the left toolbar, click <strong>Test in Web Chat</strong>. This will open a chat environment where you can interact with the bot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*4Tk05FH8dXNC-ZectzKWZg.png" /><figcaption>Test in Web Chat on Azure</figcaption></figure><p>Congratulations! You’ve successfully deployed your bot to Azure!</p><h4>Publishing your bot to Teams</h4><p>On the Azure Bot resource page, you will also see a tab called <strong>Channels</strong>. From here you can add Microsoft Teams as a channel and (if you have admin access to a Teams tenant) test your bot in a Teams environment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yq1ej4r1k_YBMnhGHqnJwQ.png" /><figcaption>Teams channel on Azure</figcaption></figure><blockquote>But what if you don’t have admin access to a Teams tenant?</blockquote><blockquote>You can create your own Microsoft developer account by signing up for a free trial of<strong> </strong><a href="https://developer.microsoft.com/en-us/microsoft-365/dev-program"><strong>Microsoft 365 E5 Developer</strong></a><strong>.</strong></blockquote><ol><li>Follow the steps to sign up and once you’re done, you should see your administrator email:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*Y1V6Nm3SQUk-rLaxMl71hA.png" /><figcaption>Microsoft 365 Developer account</figcaption></figure><p>2. Navigate back to the Azure Bot resource page and select <strong>Channels</strong>.</p><p>3. Select<em> </em><strong>Open in Teams</strong> (as seen in the screenshot above). This should prompt you to log in to your Teams admin account (this is the one you just created).</p><p>4. Once logged in, you will be able to interact with your bot in the Teams environment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wBYNkRHtrnJULXoCTXAfIA.png" /><figcaption>Teams channel on Azure</figcaption></figure><p>Great! It looks like everything is working fine in the Teams environment. Now we’re ready to publish the bot on Teams.</p><p>5. Navigate back to VS Code, open the Teams Toolkit tab and open appPackage -&gt; manifest.json</p><p>6. Update the name and description of your bot. (You can also update the developer values if you have your own links).</p><p>7. Open the browser and navigate to your <a href="https://teams.microsoft.com/v2/">Teams tenant</a>.</p><p>8. In the left toolbar, select<em> </em><strong>Developer Portal</strong><em>,</em> then click on <strong>Apps</strong> (as highlighted below):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*7AXiNulCTRutdQ1JeUR42g.png" /><figcaption>Teams Developer Portal</figcaption></figure><p>9. Select <strong>New app</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*7mHUoU8fKziWeJr8KkCkhg.png" /><figcaption>Create new app in Developer Portal</figcaption></figure><p>10. Select a <strong>name</strong> for your app.</p><p>11. Copy and paste the short and full <strong>descriptions</strong> you added in the manifest.json file. If you added a company name and URLs, you can also added them here but the minimum requirement is that you add the descriptions.</p><p>12. Save your changes (bottom of the page).</p><p>13. Copy the <strong>App ID</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yNfYM5oAqdPSjAF5JOkT5g.png" /><figcaption>App ID</figcaption></figure><p>14. Navigate back to VS Code, open the .env.dev file and assign this App ID to the variable: TEAMS_APP_ID</p><p>15. Now, open the Teams Toolkit tab and below Provision and Deploy, select <strong>Publish</strong>. This will send your app to the admin (you) for approval to publish to Teams.</p><p><strong><em>Note</em></strong><em>: You’ll need to be signed into your Microsoft 365 admin account in Teams Toolkit to do this:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jVEvujqK2t7imGSih0hGBQ.png" /><figcaption>Microsoft 365 account</figcaption></figure><p>16. Navigate to the <a href="https://admin.teams.microsoft.com/dashboard">Microsoft Teams admin centre</a> -&gt; select <strong>Teams apps</strong> from the left toolbar -&gt; select <strong>Manage apps</strong> -&gt; search for the name of your app in the search bar:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vIze84gJtiJfA1rfXV6gvQ.png" /><figcaption>Microsoft Teams admin centre</figcaption></figure><p>17. Select your app and then click the <strong>Publish</strong> button:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*O7tHjBU1XVeXXwWLWxUGWA.png" /><figcaption>Publish app to Teams</figcaption></figure><p><strong><em>Note</em></strong><em>: It may take a few hours or more to see your app in the Teams apps store.</em></p><blockquote>In the meantime you’ll find the app in the Developer Portal in your <a href="https://teams.microsoft.com/v2/">Teams tenant</a> and here you can play around with it until it’s published. Simply click on the app -&gt; select <strong><em>Preview in Teams</em></strong> -&gt; <strong><em>Add</em></strong><em>.</em></blockquote><p>18. Once the app has been published, you can search for it in Teams via the Apps tab in the left toolbar:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*tHHqQRUlY_4LmZj3BwyIDQ.png" /><figcaption>App in Teams Apps store</figcaption></figure><p>19. Click <strong>Add</strong> and a window will pop up. Click <strong>Add</strong> again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*XHDErt68ywAPr1j7jh4liA.png" /><figcaption>Add app to Teams</figcaption></figure><p>You should now see your app in the Teams toolbar and you can interact with it!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*sbg7SzEbcxLiLhH7JNHAiw.png" /><figcaption>App in Teams</figcaption></figure><p>Congratulations, you’ve <strong>developed</strong> your bot in VS code using Team Toolkit, you’ve <strong>deployed</strong> your bot to Azure, and you’ve <strong>published</strong> your bot to Teams!</p><h4>Next steps (optional)</h4><ol><li>You can <strong>customise your app via the prompt message</strong>, which you can edit in src -&gt; prompts -&gt; chat -&gt; skprompt.txt:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b6BfAh2D8i9do_15oLsYVQ.png" /><figcaption>Bot prompt</figcaption></figure><blockquote><strong>Note</strong>: Once you make changes to your bot, you’ll need to repeat the deployment process to Azure. After this deployment you’ll have to repeat the publish process, <strong>but before you publish it’s important that you update the </strong><strong>version value in the </strong><strong>manifest.json</strong>. For example, from 1.0.0 to 1.1.0.</blockquote><p>2. You can also <strong>create and use your own custom models</strong> in Azure. In this case, you can add your own <em>training data</em> to make the bot more specific to your requirements:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*md_7GmbuYQn7scjoj8YOag.png" /><figcaption>Models in Azure</figcaption></figure><p>3. You can <strong>create functions that run on certain events</strong> (such as when the user sends a message):</p><pre>// app.ts <br><br><br>// ... previous code<br>app.activity(ActivityTypes.Message, async (context: TurnContext) =&gt; {<br><br>  await context.sendActivity(&quot;You sent a message!&quot;);<br><br><br>});<br><br>// ... rest of code</pre><p>This is a very simple example where the bot will respond “<em>You sent a message!</em>” after every user message — not the most useful function but it gives you an idea of what you can do.</p><p>These were just a few ideas to get you started but there are <em>many, many</em> more ways you can customise your bot. So, get creative and enjoy building your own customised copilot! :)</p><p>If you enjoyed this resource, you can help me make more (if you can!): <a href="https://buymeacoffee.com/statlfc">https://buymeacoffee.com/statlfc</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0082ea9ae439" width="1" height="1" alt=""><hr><p><a href="https://medium.com/rewrite-tech/creating-a-teams-copilot-bot-in-azure-0082ea9ae439">Creating a Teams copilot bot in Azure</a> was originally published in <a href="https://medium.com/rewrite-tech">REWRITE TECH by Diconium</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Develop and Deploy a Chatbot in 20 minutes with Next.js and Vercel: A Step-By-Step Guide]]></title>
            <link>https://medium.com/rewrite-tech/develop-and-deploy-a-chatbot-in-20-minutes-with-next-js-and-vercel-a-step-by-step-guide-a253d5be4dfe?source=rss-9d12aafc9fb1------2</link>
            <guid isPermaLink="false">https://medium.com/p/a253d5be4dfe</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Sammy-Jo Wymer]]></dc:creator>
            <pubDate>Mon, 08 Apr 2024 14:21:36 GMT</pubDate>
            <atom:updated>2025-07-17T14:01:49.845Z</atom:updated>
            <content:encoded><![CDATA[<p>In this walkthrough you’ll learn how to develop and deploy your own custom ChatGPT-like app from scratch using Next.js and Vercel. You won’t need any prior experience with AI in development but basic knowledge of React and Next.js will be helpful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8gysJ276Ytus2LsIVU_Z5w.png" /></figure><h4>Setting up the project</h4><p><em>If you’re already familiar with setting up a Next.js app, feel free to skip ahead.</em></p><ol><li>Open your terminal then navigate to the folder where you want to create your React app (e.g. cd documents will take you to the documents folder)</li></ol><blockquote>For more information on simple terminal commands you can read my article <a href="https://medium.com/rewrite-tech/getting-friendly-with-the-terminal-a-super-friendly-beginners-guide-7ff0cd6425cd">Getting friendly with the terminal</a>.</blockquote><p>2. Once you’re in the relevant folder in the terminal, run the following command to create a Next.js app: npx create-next-app@latest</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*1ex-5U6Ok4UCWXwruoFD_Q.png" /><figcaption>Next.js setup</figcaption></figure><p><strong>The first prompt asks you to choose a project name but for the rest of the prompts you can just use the default options (as shown above).</strong></p><p><em>Great! </em>And just like that we have a functioning Next.js app.</p><p>You can see how the app looks by running npm run dev in the terminal (first make sure you’re in the app folder by running cd chat-app) and then navigating to <a href="http://localhost:3000/">http://localhost:3000</a> in your browser. You should see the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BDAaQoaEYs0RbR0a5wP6HA.png" /><figcaption>Next.js boilerplate app</figcaption></figure><p>Before we can proceed, we need to clean up some of the boilerplate code.</p><p>3. Open your newly created app in your IDE of choice. I am using <a href="https://code.visualstudio.com/">Visual Studio Code</a>. Your project should look similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w5DR8lrsqFyO0ulTInEcAw.png" /><figcaption>Next.js boilerplate code</figcaption></figure><p>4. Open the public folder and delete both of the .svg files (this folder should now be empty).</p><p>5. In src/app delete the favicon.ico.</p><p>6. Still in src/app delete the the page.module.css file, then open the globals.css file and remove all the contents so you just have an empty file.</p><p>7. Finally, open the page.tsx file, remove all the code, and add the following:</p><pre>// src/app/page.tsx<br><br>export default function Home() {<br>  return &lt;h1&gt;My Chatbot app&lt;/h1&gt;;<br>}</pre><p>Now, when you navigate back to <a href="http://localhost:3000/">http://localhost:3000</a> you should see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*hhGdeWulJcRFjDCz2AQ27w.png" /><figcaption>Next.js app</figcaption></figure><p>And that’s the initial setup done! We can now start getting our hands dirty with AI…</p><h4>Setting up OpenAI</h4><p>In this tutorial, we’ll be using the <a href="https://platform.openai.com/docs/overview">OpenAI API</a> and so you first need to make sure you have an account (if you’ve used ChatGPT then you will already have an account, if not you can easily set one up <a href="https://platform.openai.com/docs/overview">here</a>).</p><p>Login to your account and then proceed to the <a href="https://platform.openai.com/docs/overview">API</a> page. In the left sidebar click API keys and you should see a page similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UCkOB0KOOSUyqwYBk-Q3ag.png" /><figcaption>OpenAI API page</figcaption></figure><p>As you can see, I’ve already created an API key. If you don’t have one already you should create one by clicking <strong>Create new secret key</strong>.</p><p>Copy this key and then navigate back to your code. Open your terminal and export this key as an environment variable as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*muHJD5r2XhWHF0r-Psu1ww.png" /><figcaption>export openAI API key</figcaption></figure><p>Install the OpenAI Node.js library. To do this, run the following command in your terminal:<br>npm install --save openai</p><blockquote>Note: You’ll have to restart your server after this installation</blockquote><p>Great! Now we’re all ready to use this API :)</p><h4>Managing the OpenAI API</h4><p>Now that we have access to the API, we next need to ensure that the requests we make and the responses we receive are handled securely.</p><p>To do this in Next.js, we use <a href="https://nextjs.org/docs/app/building-your-application/routing/route-handlers"><strong>route handlers</strong></a>.</p><blockquote>Next.js route handlers are responsible for handling requests and generating responses in a similar way to how server-side logic operates. By encapsulating sensitive operations within route handlers, we can securely handle confidential data before responding to client requests.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*He0npSrJSHIgF7XwbbZiYw.png" /><figcaption>Route handlers in Next.js</figcaption></figure><p>1. To create our route handler, navigate to src/app and create a new folder called chat and within this folder create a file called route.ts.</p><p>2. Within this route.ts file, import and initialise the OpenAI API:</p><pre>// src/app/chat/route.ts<br><br>import OpenAI from &quot;openai&quot;;<br><br>// Assign API key to variable<br>const apiKey = process.env.OPEN_AI_KEY;<br>// Initialise OpenAI API<br>const openai = new OpenAI({ apiKey: apiKey });<br></pre><p>3. Finally, we add a POST request that will take user input (<em>questions</em>) from the frontend application and send these questions to the OpenAI API via our server, which will then return a response:</p><pre>// src/app/chat/route.ts<br><br>export async function POST(req: Request) {<br>// The &#39;question&#39; variable is the user&#39;s input from the frontend<br>  const { question } = await req.json();<br>  // Here is where we communicate with the OpenAI API to create our chatbot.<br>  // We store the chatbot&#39;s response in the &#39;response&#39; variable<br>  const response = await openai.chat.completions.create({<br>    messages: [<br>      {<br>        role: &quot;system&quot;,<br> // We give the chatbot a role with some content to determine how it will behave<br>        content:<br>          &quot;You are a helpful assistant who supports Liverpool FC&quot;,<br>      },<br>      {<br>  // We ask the chatbot to generate an answer based on the user&#39;s question<br>  // Remember, this question will come from the frontend<br>        role: &quot;user&quot;,<br>        content: question,<br>      },<br>    ],<br>  // We choose the model we want to use for our chatbot<br>    model: &quot;gpt-3.5-turbo&quot;,<br>  // We add a value for max_tokens to ensure the response won&#39;t exceed 300 tokens<br>  // This is to make sure the responses aren&#39;t too long<br>    max_tokens: 300,<br>  });<br>// Then we return the response we receive from OpenAI<br>// Note: This will only work once we set up our frontend logic<br>  return new Response(JSON.stringify(response));<br>}</pre><blockquote>Note: The code for the response variable above is almost a direct copy and paste from <a href="https://platform.openai.com/docs/quickstart?context=node">OpenAI’s quick start guide</a>:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*vNSikCSkabMZSifej-CPqg.png" /><figcaption>OpenAI API documentation</figcaption></figure><blockquote>The function in the guide above sends a request to the OpenAI API with the prompt “You are a helpful assistant”. It then console logs the response from OpenAI.</blockquote><h4>Creating your Chatbot</h4><p>So far, we’ve:</p><ol><li>Created a Next.js app from scratch.</li><li>Gained access to the OpenAI API.</li><li>Set up a route handler which sends a POST request to the OpenAI API.</li></ol><p>The final step is to take all of this and make it into a functional app.</p><p>Before we get our hands dirty with the frontend code, we’ll need to install <a href="https://axios-http.com/docs/intro">axios</a> with the following command: npm install axios — we’ll use this package to handle our HTTP requests.</p><p>Right now, we’re making a request to the OpenAI API but we don’t see any response. Let’s add our frontend functionality to see what the API can do:</p><pre>// src/app/page.tsx<br><br>// In Next.js, we need to add this line to the top of our file to declare a <br>// boundary between Server and Client Component modules. <br>&quot;use client&quot;;<br><br>// import useState so that we can update the response we get from the API<br>import { useState } from &quot;react&quot;;<br>// import axios so we can easily send the user&#39;s input to our server<br>import axios from &quot;axios&quot;;<br>import &quot;./globals.css&quot;;<br><br>const App = () =&gt; {<br>// We store and update the responses we get from the API with this state<br>// I&#39;ve added a default value to the &#39;response&#39; state that we should see <br>// when the page initially loads<br>  const [response, setResponse] = useState&lt;string&gt;(&quot;Hi there! How can I assist you?&quot;);<br>// We also store the input we get from the user in the &#39;value&#39; state and<br>// update it everytime the user types into the input field we have added below<br>  const [value, setValue] = useState&lt;string&gt;(&quot;&quot;);<br><br>// We use this function in the newly added &#39;input&#39; in the return statement.<br>// Each time the user types into the input, this function ensures that the<br>// &#39;value&#39; state is updated<br>// We also add a type to the event that we pass in<br>  const onChange = (e: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt;<br>    setValue(e.target.value);<br><br>// This function runs when the user presses the button we have added below<br>// This function takes the contents of &#39;value&#39; (the input from the user) <br>// and then sends this value to our server, which then sends a new request<br>// to the API<br>// The function then waits for the new response and updates the &#39;response&#39;<br>// value which we then display on the page<br>  const handleSubmit = async () =&gt; {<br>    const response = (await axios.post(&quot;/chat&quot;, { question: value })).data<br>      .choices[0].message.content;<br>    setResponse(response);<br>  };<br><br>// In our return statement, we add an input field so that the user can ask <br>// questions to the API.<br>// We also add a button so that the user can submit their question which then<br>// updates the response from the API<br>// We show the updated response on our page<br>return (<br>    &lt;div className=&quot;container&quot;&gt;<br>      &lt;div&gt;<br>        &lt;input<br>          type=&quot;text&quot;<br>          value={value}<br>          onChange={onChange}<br>        &gt;&lt;/input&gt;<br>      &lt;/div&gt;<br>      &lt;div&gt;<br>        &lt;button onClick={handleSubmit}&gt;Click me for answers!&lt;/button&gt;<br>      &lt;/div&gt;<br>      &lt;div&gt;<br>        &lt;p&gt;Chatbot: {response}&lt;/p&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default App;</pre><p>Now, when we navigate back to our browser, we should see a simple UI where we can ask a question:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*ZLD0t9bT3jT9tWBglc78ZA.png" /><figcaption>OpenAI response on webpage</figcaption></figure><p><em>Aaaand it works</em> :) we essentially have our (<em>pretty ugly</em>) version of ChatGPT up and running, but that’s not even the coolest part.</p><p>We can customise our chatbot any way we want. I’m a huge Liverpool fan and so I’m going to customise my chatbot to be a fellow LFC fan who has a similar personality to one of my favourite players — Darwin Nunez.</p><p>This is where you can get creative and decide what type of ‘personality’ you want your chatbot to have. You can do this by editing the content of the &quot;system” role in src/app/chat/route.ts:</p><pre>// src/app/chat/route.ts<br><br>// ...other code<br><br>  const response = await openai.chat.completions.create({<br>    messages: [<br>      {<br>        role: &quot;system&quot;,<br>        content:<br>          &quot;You love Liverpool FC. Your name is Darwizzy and you have a <br>personality similar to Darwin Nunez (a football player who currently plays <br>for Liverpool). You have latin and scouse humour.&quot;,<br>      },<br>      {<br>        role: &quot;user&quot;,<br>        content: question,<br>      },<br>    ],<br>    model: &quot;gpt-3.5-turbo&quot;,<br>    max_tokens: 300,<br>  });<br><br>// ... other code</pre><p>So, how is it looking?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*T69SNGQU5YJNdLBAnQZ3rQ.png" /><figcaption>customised chatbot in React</figcaption></figure><p>Haha. I love it.</p><p>Time to make Darwizzy look a bit nicer though.</p><p>Navigate to the globals.css file and copy and paste the following code:</p><pre>/* src/app/globals.css */<br><br>* {<br>  box-sizing: border-box;<br>  text-align: center;<br>  font-family: &quot;Segoe UI&quot;, Tahoma, Geneva, Verdana, sans-serif;<br>}<br><br>body {<br>  background-color: rgb(39, 40, 41);<br>}<br><br>input {<br>  width: 100%;<br>  padding: 1em;<br>  margin-bottom: 1em;<br>  border: 0.15em solid #ccc;<br>  border-radius: 0.25em;<br>  font-size: 1.2em;<br>}<br><br>button {<br>  width: 100%;<br>  padding: 1em;<br>  background-color: #d60000;<br>  color: #fff;<br>  border: none;<br>  border-radius: 0.25em;<br>  cursor: pointer;<br>  transition: background-color 0.3s ease-in-out;<br>  font-size: 1.2em;<br>  box-shadow: 0 0.25em 0.25em rgba(0, 0, 0, 0.1);<br>}<br><br>button:hover {<br>  background-color: #b20000;<br>}<br><br>p {<br>  margin-top: 1em;<br>  padding: 1em;<br>  background-color: #ffffff;<br>  border-radius: 0.25em;<br>  font-size: 1.2em;<br>  box-shadow: 0 1em 0.25em rgba(0, 0, 0, 0.1);<br>}<br><br>.container {<br>  max-width: 35em;<br>  margin: auto;<br>  margin-top: 1em;<br>  margin-bottom: 2em;<br>  padding: 2em;<br>  border: 0.3em solid #b20000;<br>  border-radius: 0.5em;<br>  background-color: #f5f5f5;<br>}<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*awS_W04KyS1B6X96p31qUQ.png" /><figcaption>Next.js chatbot app</figcaption></figure><p>You can see that I’m no UI/UX designer but it’s enough to get you started!</p><p>You did it! Well done! You’ve managed to integrate AI into a Next.js app.</p><p>And it’s just the beginning. Now you have this solid foundation, you can customise it even more and add even more functionality :)</p><h4>Deploying your chatbot</h4><p>Now you have your chatbot working locally, but why not share it with the world?</p><p>You can deploy your Next.js app for free using <a href="https://vercel.com/signup?utm_source=next-site&amp;utm_medium=deploy-on-vercel-cta&amp;utm_campaign=learn_basics_create-nextjs-app_setup-cta-signup">Vercel</a>.</p><p>First of all, you’ll need to push your code to <a href="https://github.com/">GitHub</a>. If you know how to do this already feel free to skip ahead. Otherwise, navigate to your GitHub profile, then to <strong>Repositories</strong>, and then click the green <strong>New</strong> button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*ixyc07jCQigrbiCc21OnOw.png" /><figcaption>Create a GitHub repository</figcaption></figure><p>Add the name of your repository and then click the green <strong>Create repository</strong> button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eUnvRJC8cL8xNTuOcqfSGA.png" /><figcaption>Create a GitHub repository</figcaption></figure><p>Copy the highlighted code above and run it in your terminal to push your existing code. Now your code exists on GitHub, you can deploy and host it via Vercel.</p><p>Navigate to <a href="https://vercel.com/signup?utm_source=next-site&amp;utm_medium=deploy-on-vercel-cta&amp;utm_campaign=learn_basics_create-nextjs-app_setup-cta-signup">this link</a> and create an account if you don’t already have one.</p><p>Once you’re all set up, you’ll need to add a new project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qADTB-KnFbS9V9BUzTuH_A.png" /><figcaption>Vercel dashboard</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-pgFGY6hZ9W1pSY3Txk5jA.png" /><figcaption>Vercel — add new project</figcaption></figure><p>If you haven’t already, you’ll have to give Vercel permission for either all or some of your repositories. I chose <strong>select repositories</strong> and then selected my <strong>chatbot</strong> repository.</p><p>Then click the green <strong>Install</strong> button.</p><p>Once you’ve allowed permissions for one or more repositories you’ll be able to import these. Click the <strong>import</strong> button for your chatbot repository.</p><p>You’ll be asked to choose a name for your project and you also need to add the OpenAI key as an environment variable here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*WO_IlmJR9hdVLwDE3cAqgQ.png" /></figure><blockquote>Note: You can see your OPEN_AI_KEY by running this command in your terminal: echo $OPENAI_API_KEY</blockquote><p>Then click <strong>Deploy</strong>.</p><p>Congratulations! You have successfully created and deployed a chatbot app! You can find the URL for your new app on your Vercel dashboard.</p><p>For example mine is <a href="https://chat-lfc.vercel.app/">https://chat-lfc.vercel.app/</a>.</p><p>Now, every time you push code changes to your GitHub main branch, Vercel will automatically redeploy your app with these changes! :)</p><h4>I hope you found this walkthrough useful and I’d love to hear your feedback!</h4><p>#YNWA</p><p>If you enjoyed this resource, you can help me make more (if you can!): <a href="https://buymeacoffee.com/statlfc">https://buymeacoffee.com/statlfc</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a253d5be4dfe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/rewrite-tech/develop-and-deploy-a-chatbot-in-20-minutes-with-next-js-and-vercel-a-step-by-step-guide-a253d5be4dfe">Develop and Deploy a Chatbot in 20 minutes with Next.js and Vercel: A Step-By-Step Guide</a> was originally published in <a href="https://medium.com/rewrite-tech">REWRITE TECH by Diconium</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Fullstack Chatbot in 20 minutes with React and Node.js: A Step-By-Step Guide]]></title>
            <link>https://medium.com/rewrite-tech/build-your-own-fullstack-chatbot-with-react-and-node-js-a-step-by-step-guide-922b392bfbf2?source=rss-9d12aafc9fb1------2</link>
            <guid isPermaLink="false">https://medium.com/p/922b392bfbf2</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Sammy-Jo Wymer]]></dc:creator>
            <pubDate>Wed, 21 Feb 2024 14:11:30 GMT</pubDate>
            <atom:updated>2025-07-17T14:02:11.682Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s 2024 and AI and chatbots are no longer just buzzwords — they’re necessities in software development. With this walkthrough, you’ll learn how to create your own custom ChatGPT-like app from scratch using React and Node.js. You won’t need any prior experience with AI in development but basic knowledge of React and Node.js will be helpful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KVt4KODHm6vrbM2D2w7c_g.png" /></figure><h4>Setting up the project</h4><p><em>If you’re already familiar with setting up a React app, feel free to skip ahead.</em></p><p>To begin, we need to set up our <a href="https://react.dev/">React</a> project. One of the simplest and fastest ways to do this is with <a href="https://vitejs.dev/guide/">Vite</a>.</p><blockquote>In the past I always used <a href="https://create-react-app.dev/">Create React App</a> but I recently turned to Vite for a much faster and efficient way of setting up my React app. The documentation is also really easy to follow.</blockquote><p>1. Open your terminal then navigate to the folder where you want to create your React app (e.g. cd documents will take you to the documents folder).</p><blockquote>For more information on simple terminal commands you can read my article <a href="https://medium.com/rewrite-tech/getting-friendly-with-the-terminal-a-super-friendly-beginners-guide-7ff0cd6425cd">Getting friendly with the terminal</a>.</blockquote><p>2. Once you’re in the relevant folder in the terminal, run the following command and then follow the instructions in the terminal:<br>npm create vite@latest</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*22dHbO_mH2FkBBOpmVG3gQ.png" /><figcaption>Vite instructions in terminal</figcaption></figure><p>The above screenshot shows my terminal and the folder I’m in (dev/2024). Vite will ask you to name your project (as you can see, I named it ai-in-react) and then select a framework. Select React and then TypeScript and then run the commands that Vite provides to complete the setup.</p><p><em>Great! </em>And just like that we have a functioning React app. But before we can proceed, we need to clean up/delete some of the boilerplate code that comes with the Vite setup.</p><p>3. Open your newly created app in your IDE of choice. I am using <a href="https://code.visualstudio.com/">Visual Studio Code</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MFKi_eHLG7UGB1WH6LUk-w.png" /><figcaption>ai-in-react app in Visual Studio Code</figcaption></figure><p>Delete the public and assets folders (highlighted in the screenshot below) and also the index.css file (don’t forget to remove the import for this file in main.tsx).</p><p>Then open the App.css file and delete all the contents (we’ll add our own later).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aR0YbcmQVsvf8yy0lLO7fA.png" /><figcaption>Remove Vite boilerplate</figcaption></figure><p>Navigate to the index.html file and remove the link for the Vite icon (highlighted in the screenshot below).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v6OiZFYR496mJgL3CrKxUg.png" /><figcaption>Remove Vite boilerplate</figcaption></figure><p>Finally, open the App.tsx file and remove the first three imports (leaving only the import for App.css). Remove the rest of the functionality leaving only an empty App function (highlighted in red in the screenshot below).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YnFRep3hk-CHnJ1fJPzTkw.png" /><figcaption>Remove Vite boilerplate</figcaption></figure><p>Your App.tsx should now contain the following code (and if you’re running the app on your local server, you should see a blank white page).</p><p>Notice I also changed the &lt;&gt;&lt;/&gt; to a div and have added a className:</p><pre>// App.tsx<br><br>import &quot;./App.css&quot;;<br><br>function App() {<br>  return &lt;div className=&quot;container&quot;&gt;&lt;/div&gt;;<br>}<br>export default App;</pre><p>That’s the initial setup done! We can now start getting our hands dirty with AI…</p><h4>Setting up OpenAI</h4><p>In this tutorial, we’ll be using the <a href="https://platform.openai.com/docs/overview">OpenAI API</a> and so you first need to make sure you have an account (if you’ve used ChatGPT then you will already have an account, if not you can easily set one up <a href="https://platform.openai.com/docs/overview">here</a>).</p><p>Login to your account and then proceed to the <a href="https://platform.openai.com/docs/overview">API</a> page. In the left sidebar click API keys and you should see a page similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UCkOB0KOOSUyqwYBk-Q3ag.png" /><figcaption>OpenAI API page</figcaption></figure><p>As you can see, I’ve already created an API key. If you don’t have one already you should create one by clicking <strong>Create new secret key</strong>.</p><p>Copy this key and then navigate back to your code. In the root, create a file called .env and add your key as a variable here. For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*K2aaoZhDQpdy0x38yvuq2Q.png" /><figcaption>.env file with API key</figcaption></figure><blockquote>When using Vite, variables within the <em>.env</em> file should be prefixed with <em>VITE_</em>. For example, <em>VITE_OPEN_AI_KEY</em></blockquote><p>Install the OpenAI Node.js library. To do this, run the following command in your terminal:<br>npm install openai</p><p>Great! Now we’re all ready to use this API :)</p><h4>Setting up a local server</h4><p>We need to create a local server to manage our API requests and ensure any data we provide to the API is handled securely.</p><p>Creating a server might sound like a daunting task if you’ve never done it before, but we’re going to do it in 6 easy steps.</p><ol><li>First, in the root, create a file called server.js.</li><li>Then in your terminal, install <a href="https://expressjs.com/">express</a> with the following command:<br>npm install express — this is the package we’ll use to create our web server.</li><li>Install cors with the following command: npm install cors — this package will allow our frontend and server to interact without issue.</li><li>Add <strong>express</strong> and <strong>cors</strong> as imports in the server.js file and create your local server with the following code:</li></ol><pre>// server.js<br><br>import express from &quot;express&quot;;<br>import cors from &quot;cors&quot;;<br><br>// Initialise express<br>const app = express();<br>// Here, we provide a port. You can choose any available port. <br>const port = process.env.PORT || 3005;<br><br>// We add this so that our server and frontend app can interact without issue<br>app.use(cors());<br>// We add this line to parse JSON in the request body<br>app.use(express.json()); <br>// This allows us to see if our server is running ok<br>app.listen(port, () =&gt; {<br>  console.log(`Server running on port ${port}`);<br>});</pre><p>5. Now, we import and initialise the OpenAI API:</p><pre>// server.js<br><br>import express from &quot;express&quot;;<br>import cors from &quot;cors&quot;;<br>import { OpenAI } from &quot;openai&quot;;<br><br>const app = express();<br>const port = process.env.PORT || 3005;<br>// Assign API key to variable<br>const apiKey = process.env.VITE_OPEN_AI_KEY;<br>// Initialise OpenAI API<br>const openai = new OpenAI({ apiKey: apiKey });<br><br>app.use(cors());<br>app.use(express.json()); <br>app.listen(port, () =&gt; {<br>  console.log(`Server running on port ${port}`);<br>});</pre><p>6. Finally, we add a POST request that will take user input (<em>questions</em>) from the frontend application and send these questions to the OpenAI API via our server, which will then return a response:</p><pre>// server.js<br><br>import express from &quot;express&quot;;<br>import cors from &quot;cors&quot;;<br>import { OpenAI } from &quot;openai&quot;;<br><br>const app = express();<br>const port = process.env.PORT || 3005;<br>const apiKey = process.env.VITE_OPEN_AI_KEY;<br>const openai = new OpenAI({ apiKey: apiKey });<br><br>app.use(cors());<br>app.use(express.json()); <br>app.listen(port, () =&gt; {<br>  console.log(`Server running on port ${port}`);<br>});<br><br>// Here, we define the &#39;/chatbot&#39; route to handle questions from our <br>// frontend React application<br>app.post(&quot;/chatbot&quot;, async (req, res) =&gt; {<br>// The &#39;question&#39; variable is the user&#39;s input from the frontend<br>  const { question } = req.body;<br>  // Here is where we communicate with the OpenAI API to create our chatbot.<br>  // We store the chatbot&#39;s response in the &#39;response&#39; variable<br>  const response = await openai.chat.completions.create({<br>    messages: [<br>  // We give the chatbot a role with some content to determine how it will behave<br>      {<br>        role: &quot;system&quot;,<br>        content:<br>          &quot;You are a helpful assistant.&quot;,<br>      },<br>  // We ask the chatbot to generate an answer based on the user&#39;s question<br>  // Remember, this question will come from the frontend<br>      {<br>        role: &quot;user&quot;,<br>        content: question,<br>      },<br>    ],<br>  // We choose the model we want to use for our chatbot<br>    model: &quot;gpt-3.5-turbo&quot;,<br>  // We add a value for max_tokens to ensure the response won&#39;t exceed 300 tokens<br>  // This is to make sure the responses aren&#39;t too long<br>    max_tokens: 300,<br>  });<br>// Then we take the text response and display it on the server<br>// Note: This will only work once we set up our frontend logic<br>  res.send(response.choices[0].message.content);<br>});</pre><p>The code for the response variable above is almost a direct copy and paste from <a href="https://platform.openai.com/docs/quickstart?context=node">OpenAI’s quick start guide</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N0pxPFJus9gTWJljbzjP0g.png" /><figcaption>OpenAI API documentation</figcaption></figure><blockquote>The function in the guide above sends a request to the OpenAI API with the prompt “<em>You are a helpful assistant</em>”. It then console logs the response from OpenAI.</blockquote><p>You can check that your server is working by running: node server.js in the terminal. You should then see a message in the terminal which says: Server running on port 3005</p><p>Now that our server is up and running we can finally move on to creating our chatbot in React.</p><h4>Creating your React Chatbot</h4><p>So far, we’ve:<br>- Created a React app from scratch using Vite<br>- Gained access to the OpenAI API and integrated it into our code <br>- Set up our own local server to manage our chatbot</p><p>Before we get our hands dirty with the frontend code, we’ll need to install <a href="https://axios-http.com/docs/intro">axios</a> with the following command: npm install axios — we’ll use this package to handle our HTTP requests.</p><p>Let’s now go back to our App.tsx file and add the necessary functionality to get our chatbot up and running.</p><pre>// App.tsx<br><br>// import useState so that we can update the response we get from the API<br>import { useState } from &quot;react&quot;;<br>// import axios so we can easily send the user&#39;s input to our server<br>import axios from &quot;axios&quot;;<br>import &quot;./App.css&quot;;<br><br>function App() {<br>// We store and update the responses we get from the API with this state<br>// I&#39;ve added a default value to the &#39;response&#39; state that we should see <br>// when the page initially loads<br>  const [response, setResponse] = useState&lt;string&gt;(&quot;Hi there! How can I assist you?&quot;);<br>// We also store the input we get from the user in the &#39;value&#39; state and<br>// update it everytime the user types into the input field we have added below<br>  const [value, setValue] = useState&lt;string&gt;(&quot;&quot;);<br><br>// We use this function in the newly added &#39;input&#39; in the return statement.<br>// Each time the user types into the input, this function ensures that the<br>// &#39;value&#39; state is updated<br>// We also add a type to the event that we pass in<br>  const onChange = (e: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt;<br>    setValue(e.target.value);<br><br>// This function runs when the user presses the button we have added below<br>// This function takes the contents of &#39;value&#39; (the input from the user) <br>// and then sends this value to our server, which then sends a new request<br>// to the API<br>// The function then waits for the new response and updates the &#39;response&#39;<br>// value which we then display on the page<br>const handleSubmit = async () =&gt; {<br>    const response = await axios.post(&quot;http://localhost:3005/chatbot&quot;, {<br>      question: value,<br>    });<br>    setResponse(response.data);<br>  };<br><br>// In our return statement, we add an input field so that the user can ask <br>// questions to the API<br>// We also add a button so that the user can submit their question which then<br>// updates the response from the API<br>// We show the updated response on our page<br>return (<br>    &lt;div className=&quot;container&quot;&gt;<br>      &lt;div&gt;<br>        &lt;input<br>          type=&quot;text&quot;<br>          value={value}<br>          onChange={onChange}<br>        &gt;&lt;/input&gt;<br>      &lt;/div&gt;<br>      &lt;div&gt;<br>        &lt;button onClick={handleSubmit}&gt;Click me for answers!&lt;/button&gt;<br>      &lt;/div&gt;<br>      &lt;div&gt;<br>        &lt;p&gt;Chatbot: {response}&lt;/p&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default App;</pre><p>We finally have some frontend functionality!</p><p>To see how it works so far, make sure your server is running then open a new terminal and run the development server with the following command: npm run dev</p><p>Finally, open your browser of choice and navigate to <a href="http://localhost:5173/">http://localhost:5173</a> where you should see the following (<em>very ugly</em>) UI:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*kemc1t6_EDul0QZE4DBMyQ.png" /><figcaption>chatbot running on local server</figcaption></figure><p>So… does it work? Let’s ask it a question…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*BbbNGg6-aslGElqtyRwGew.png" /><figcaption>chatbot response on local server</figcaption></figure><p><em>It works</em> :) we essentially have our (pretty ugly) version of ChatGPT up and running, but that’s not even the coolest part…</p><p>We can customise our chatbot any way we want. I’m a huge Liverpool fan and so I’m going to customise my chatbot to be a fellow LFC fan who has a similar personality to one of my favourite players — Darwin Nunez.</p><p>This is where you can get creative and decide what type of ‘personality’ you want your chatbot to have. You can do this by editing the content of the &quot;system” role in server.js:</p><pre>// server.js<br><br>const response = await openai.chat.completions.create({<br>    messages: [<br>      {<br>        role: &quot;system&quot;,<br>        content:<br>          &quot;You love Liverpool FC. Your name is Darwizzy and you have a <br>            personality similar to Darwin Nunez <br>            (a football player who currently plays for Liverpool). <br>            You have Latin and Scouse humour.&quot;,<br>      },<br>      {<br>        role: &quot;user&quot;,<br>        content: question,<br>      },<br>    ],<br>    model: &quot;gpt-3.5-turbo&quot;,<br>    max_tokens: 300,<br>  });<br>  res.send(response.choices[0].message.content);<br>});</pre><p>So, how is it looking?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*EmDdA53ZG8CIiCM1FrPALQ.png" /><figcaption>customised chatbot in React</figcaption></figure><blockquote>Note: When you make changes in the <em>server.js</em> file, you’ll have to restart your server to see these changes. To avoid this, you can install <a href="https://www.npmjs.com/package//nodemon">nodemon</a> with the following command: npm install -g nodemon <strong><br></strong>After this package is installed, restart your server with: nodemon server.js</blockquote><p>Haha. I love it.</p><p>Time to make Darwizzy look a bit nicer.</p><p>Navigate to the App.css file and copy and paste the following code:</p><pre>// App.css<br><br>* {<br>  box-sizing: border-box;<br>  text-align: center;<br>  font-family: &quot;Segoe UI&quot;, Tahoma, Geneva, Verdana, sans-serif;<br>}<br><br>body {<br>  background-color: rgb(39, 40, 41);<br>}<br><br>input {<br>  width: 100%;<br>  padding: 1em;<br>  margin-bottom: 1em;<br>  border: 0.15em solid #ccc;<br>  border-radius: 0.25em;<br>  font-size: 1.2em;<br>}<br><br>button {<br>  width: 100%;<br>  padding: 1em;<br>  background-color: #d60000;<br>  color: #fff;<br>  border: none;<br>  border-radius: 0.25em;<br>  cursor: pointer;<br>  transition: background-color 0.3s ease-in-out;<br>  font-size: 1.2em;<br>  box-shadow: 0 0.25em 0.25em rgba(0, 0, 0, 0.1);<br>}<br><br>button:hover {<br>  background-color: #b20000;<br>}<br><br>p {<br>  margin-top: 1em;<br>  padding: 1em;<br>  background-color: #ffffff;<br>  border-radius: 0.25em;<br>  font-size: 1.2em;<br>  box-shadow: 0 1em 0.25em rgba(0, 0, 0, 0.1);<br>}<br><br>.container {<br>  max-width: 35em;<br>  margin: auto;<br>  margin-top: 15em;<br>  padding: 2em;<br>  border-radius: 0.5em;<br>  background-color: #f5f5f5;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*4TjKar-s_uYngrcd7xsgEA.png" /><figcaption>simple chatbot app in React</figcaption></figure><p>You can see that I’m no UI/UX designer but it’s enough to get you started!</p><p>You did it! Well done! You’ve managed to integrate AI into a React app to create your own chatbot, which runs on a local server!</p><p>And it’s just the beginning. Now you have this solid foundation, you can customise the chatbot even more and develop the application even further :)</p><h4>I hope you found this walkthrough useful and I’d love to hear your feedback!</h4><p>If you enjoyed this resource, you can help me make more (if you can!): <a href="https://buymeacoffee.com/statlfc">https://buymeacoffee.com/statlfc</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=922b392bfbf2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/rewrite-tech/build-your-own-fullstack-chatbot-with-react-and-node-js-a-step-by-step-guide-922b392bfbf2">Build a Fullstack Chatbot in 20 minutes with React and Node.js: A Step-By-Step Guide</a> was originally published in <a href="https://medium.com/rewrite-tech">REWRITE TECH by Diconium</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 ways to excel as a Software Engineer in 2025]]></title>
            <link>https://medium.com/rewrite-tech/3-ways-to-excel-as-a-software-engineer-in-2024-18ecda06d2fa?source=rss-9d12aafc9fb1------2</link>
            <guid isPermaLink="false">https://medium.com/p/18ecda06d2fa</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[careers]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Sammy-Jo Wymer]]></dc:creator>
            <pubDate>Thu, 18 Jan 2024 15:43:35 GMT</pubDate>
            <atom:updated>2025-07-17T14:02:49.672Z</atom:updated>
            <content:encoded><![CDATA[<p>The world of software development is a pretty great one, but with increasingly more supply than demand, how can you excel as a software engineer in 2025?</p><h3>Diversify your work</h3><p>As wonderful as it would be, working as a software engineer doesn’t always mean working on code all day, every day. There is much more to the role, and the more you can diversify yourself within this role, the more <strong>resilient</strong> and <strong>marketable</strong> you’ll be as a software engineer.</p><p>For example, one way to <em>add tools to your programming belt</em> is to write technical articles. These articles could be about things you’ve learned while working on certain features or bugs, new or upcoming features of a programming language that you use at work, or tutorials for certain frameworks or software.</p><blockquote>Actively trying to explain a topic forces you to really understand it as opposed to ‘passively’ watching tutorials and not really taking in the information.</blockquote><p>By writing these articles, not only are you deepening your own knowledge of these topics, you are also<strong> creating a tangible library of resources that you can use as evidence to showcase your knowledge and skills</strong>, whether this be to potential employers or when negotiating your next salary. You’re also building up resources for your company, which benefits everyone.</p><blockquote>If writing isn’t your ‘thing’ then you could showcase these skills and knowledge via presentations, which we’ll go further into in the next section.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EkmDX8eQrbYlMr5FMH_ytA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@aisvri?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">aisvri</a> on <a href="https://unsplash.com/photos/red-blue-and-yellow-electric-wires-c4wkzZcPxHE?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>Having diversity in your work is really helpful when you’re feeling ‘burned-out’ from working on code. Not only does it give your brain something else to focus on, it also helps to develop other ‘soft’ skills that will make you an overall better developer, employee, and more valuable asset to the programming world.</p><p>In this way, you’re able to contribute, even if it’s not directly code related. The bonus being that you create and share content both internally and externally, which leads us nicely into the next section…</p><h3>Showcase your skills</h3><p>Within your company, you can showcase your skills through <strong>developer exchanges.</strong> These could be smaller or larger group meetings that occur once or twice a month, where developers exchange knowledge with each other.</p><p>By participating in such exchanges, not only will you develop technical knowledge and presentation skills, but you’ll also <strong>gain more visibility within your company</strong>. This visibility may lead you to other company projects where you can further utilise and expand your tech stack.</p><blockquote>I also use these developer exchanges to learn about new topics. I usually decide on a topic that I want to learn more about and then sign up to share this knowledge within the exchange the following month.</blockquote><blockquote>This way, I put ‘healthy pressure’ on myself to learn enough about the topic that I can explain and discuss it with other developers. Again, this leads nicely into the next section…</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nROgwpRtT3mVT1d_cACifA.jpeg" /><figcaption>Photo by Canva Studio: <a href="https://www.pexels.com/photo/woman-sharing-her-presentation-with-her-colleagues-3153198/">https://www.pexels.com/photo/woman-sharing-her-presentation-with-her-colleagues-3153198/</a></figcaption></figure><h3>Sharpen your programming skills</h3><p>The articles, presentations, and exchanges are great for developing your knowledge of certain topics. The next step is to use this knowledge to do what software engineers were born to do *<em>puts on sunglasses</em>* — <strong>code</strong>.</p><p>Working on a small, independent project that utilises the language/tools/framework you’ve been learning is the perfect way to really sharpen these skills.</p><p>Before starting on a project, be sure to decide on one that you genuinely find interesting, and one which will be useful for you or the company.</p><p><em>(…how many times have we started a new project and then left it to die the following week…?)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dEYhTT6LxQL3CGxex1aFWQ.jpeg" /><figcaption>Photo by Miesha Renae Maiden: <a href="https://www.pexels.com/photo/top-view-photo-of-notebook-and-laptop-390573/">https://www.pexels.com/photo/top-view-photo-of-notebook-and-laptop-390573/</a></figcaption></figure><p>This will also provide another opportunity for you to showcase your skills to your colleagues, by talking them through your project, the code, and how it works. It will also allow you to <strong>practice dormant skills while developing new ones</strong>.</p><p>You can also showcase this project externally (e.g. via <a href="https://github.com/">GitHub</a>) and gain even more visibility in the programming world. This will increase your marketability further, and can also help to expand your network and reach.</p><h4>So, this year, why not give these three steps a go and take your software development career to new levels.</h4><p>If you enjoyed this resource, you can help me make more (if you can!): <a href="https://buymeacoffee.com/statlfc">https://buymeacoffee.com/statlfc</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18ecda06d2fa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/rewrite-tech/3-ways-to-excel-as-a-software-engineer-in-2024-18ecda06d2fa">3 ways to excel as a Software Engineer in 2025</a> was originally published in <a href="https://medium.com/rewrite-tech">REWRITE TECH by Diconium</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is React Compiler?]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/rewrite-tech/what-is-react-forget-00fdd742636c?source=rss-9d12aafc9fb1------2"><img src="https://cdn-images-1.medium.com/max/1920/1*Z4wr_0SayoWDk2VYcdcHpQ.png" width="1920"></a></p><p class="medium-feed-snippet">The concept of React Forget was introduced during React Conf. 2021 and has recently been renamed to React Compiler.</p><p class="medium-feed-link"><a href="https://medium.com/rewrite-tech/what-is-react-forget-00fdd742636c?source=rss-9d12aafc9fb1------2">Continue reading on REWRITE TECH by Diconium »</a></p></div>]]></description>
            <link>https://medium.com/rewrite-tech/what-is-react-forget-00fdd742636c?source=rss-9d12aafc9fb1------2</link>
            <guid isPermaLink="false">https://medium.com/p/00fdd742636c</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[guid]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Sammy-Jo Wymer]]></dc:creator>
            <pubDate>Fri, 01 Dec 2023 11:57:52 GMT</pubDate>
            <atom:updated>2025-07-17T13:58:56.957Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Why taking microbreaks is better than ‘powering through’]]></title>
            <link>https://medium.com/rewrite-tech/why-taking-microbreaks-is-better-than-powering-through-4ec8100f140b?source=rss-9d12aafc9fb1------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ec8100f140b</guid>
            <category><![CDATA[design]]></category>
            <category><![CDATA[mental-health]]></category>
            <category><![CDATA[mindfulness]]></category>
            <category><![CDATA[work]]></category>
            <category><![CDATA[remote-working]]></category>
            <dc:creator><![CDATA[Sammy-Jo Wymer]]></dc:creator>
            <pubDate>Tue, 21 Nov 2023 15:34:48 GMT</pubDate>
            <atom:updated>2025-07-17T14:03:11.361Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cR_5UAtNwd0QkClWsHXJcQ.png" /></figure><p>It’s Monday and I’m sure you have a lot to do today. I certainly do…</p><p>But this week, try and be more mindful of how you go about your work. You might think that you’ll get more work done by skipping breaks, or eating lunch at your desk while working, but you’re actually more likely to be productive if you take that break.</p><h3>Break time isn’t lost time…</h3><p>When I first started my remote job, I wanted to take advantage of the flexibility we have with our working hours. This meant that I never took a break because I wanted to finish earlier.</p><p>At first, this felt like a cheat code but I quickly found that not taking a break exhausts you physically and mentally. Short-term you feel really tired, but long-term the symptoms get even worse. The time you think you gained from not taking a break is then spent trying to regain the extra energy you used to power through.</p><h3>You’ll actually learn more if you take breaks…</h3><p><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7024394/">Research</a> shows we retain information better when we give our brain time to process it. Instead of cramming our brain with information for 2 hours straight, turn this into 30 minute chunks, taking short breaks in between to let the information sink in. Whatever type of person you are — a yoga guru, a meditator, a walker, a runner, a music lover, etc. — you could do any of these things during learning breaks to help facilitate learning.</p><p>This <a href="https://www.instagram.com/reel/Cx_HMOeMOiT/?utm_source=ig_web_copy_link&amp;igshid=MzRlODBiNWFlZA==">video</a> explains how being mobile during your breaks can vastly improve your health, and overall quality of life.</p><h3>What if I’m stuck on a problem and I need to get it solved quickly?</h3><p>Good question.</p><p>Instead of cramming more information into your brain, give it some space to work and the solution is more likely to come to you. As a software developer, I’ve experienced this so many times when stepping away from a seemingly impossible bug. I walk away and then the solutions pops into my head. (This isn’t magic by the way, it’s <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7024394/">science</a>).</p><h4>The takeaway: Less can be more</h4><p>We all want to work fast and find solutions but maybe we already have the solution, just not the brain space to process it. Take the break. Give yourself this space.</p><p>If you enjoyed this resource, you can help me make more (if you can!): <a href="https://buymeacoffee.com/statlfc">https://buymeacoffee.com/statlfc</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ec8100f140b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/rewrite-tech/why-taking-microbreaks-is-better-than-powering-through-4ec8100f140b">Why taking microbreaks is better than ‘powering through’</a> was originally published in <a href="https://medium.com/rewrite-tech">REWRITE TECH by Diconium</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Utilising your senses to become a better developer ️  ️]]></title>
            <link>https://medium.com/rewrite-tech/stop-look-listen-utilising-your-senses-to-become-a-better-developer-%EF%B8%8F-%EF%B8%8F-829ff9ec703c?source=rss-9d12aafc9fb1------2</link>
            <guid isPermaLink="false">https://medium.com/p/829ff9ec703c</guid>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[neuroscience]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Sammy-Jo Wymer]]></dc:creator>
            <pubDate>Thu, 21 Sep 2023 12:23:39 GMT</pubDate>
            <atom:updated>2025-07-17T14:03:28.454Z</atom:updated>
            <content:encoded><![CDATA[<p>As developers, one of the biggest challenges we face is <strong>maintaining focus</strong>. No matter if we’re working from the office or from home, we are constantly surrounded by external stimuli which serve as distractions.</p><p>This could be a conversation between colleagues, the <em>ping</em> of Teams messages being exchanged, the notification bar showing yet another email, or the post worker delivering those Reese’s peanut butter cups you ordered while you were menstruating/manstruating at the weekend… 🥸</p><p>So, when we are constantly being bombarded with a multitude of sensory stimuli while working, <strong>how on earth are we supposed to main focus and absorb information</strong>?</p><p>Let me introduce to you: <strong>multisensory integration</strong>. This article will use practical examples to explain what multisensory integration is and how you, as a developer, can <strong>utilise it to improve your overall focus and learning</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cI_9nt8GWPgmoTM-fnSCIg.png" /></figure><h4>What is multisensory integration?</h4><p>We perceive the world through multiple senses (<em>e.g. sight, sound, touch, smell, taste</em>). Multisensory integration is the process of <strong>combining</strong> the information we receive from<strong> two or more</strong> of these senses, to help us build up a more <strong>robust</strong> <strong>picture</strong> of what’s happening around us. 🖼️</p><p>Imagine we already ate the Reese’s cups delivery we received this morning and now have to venture to the shop across the street to buy more snacks :(</p><p>Imagine now you’re crossing the road and the only sensory information you have is visual (<em>maybe you’re wearing headphones</em>). This is fine — it’s enough information for us to safely cross the road… 🦺</p><p>Imagine again that you’re crossing the road but this time you have both vision and sound to help you. Of course, this makes crossing the road a lot easier. <br><em>(You may have even been in a situation before where you took off your headphones to cross the street because it made it ‘easier’.) 🎧</em></p><p>The reason it’s <em>easier</em> is because this additional sensory information allows you to make a <strong>faster decision</strong> on whether it’s safe to cross the road, due to increased sensory ‘evidence’. 🧪</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AdwporZ-k_MSfo8xL35yBA.jpeg" /><figcaption>Photo by Lukas Hartmann: <a href="https://www.pexels.com/photo/man-in-gray-hooded-jacket-walking-on-gray-bricks-pavement-907526/">https://www.pexels.com/photo/man-in-gray-hooded-jacket-walking-on-gray-bricks-pavement-907526/</a></figcaption></figure><h4>How does this relate to software development?</h4><p>As developers, we’re constantly having to digest new information, whether this be a new programming language, updated documentation from an old programming language, or the <em>millions of articles </em>we receive in our inboxes each day from all those newsletter we signed up to.</p><p>Instead of relying <em>solely</em> on the <strong>visual</strong> aspect of reading these articles (<em>which, let’s face it, we </em><strong><em>always</em></strong><em> have to read multiple times because we lose focus</em>), you could also add an auditory element by <strong>using a screen reader</strong>.</p><p><strong>In doing this, you’re adding another sensory element to your learning, which will result in the information being processed more efficiently. <br></strong><em>(You’ll also find that you don’t have to read the same line 5 times to get it to stick…)</em></p><blockquote><strong>The auditory sense is an underutilised one amongst software developers</strong>, but it can truly make you a better developer when applied properly.👂</blockquote><p>Consider pair programming: in these sessions, you typically explain your thought processes and code logic to colleagues. <em>You verbalise them</em>. In doing so, you <strong>reinforce your own understanding</strong> and improve your learning.</p><blockquote>Other combinations of sensory input such as <strong>listening to a tutorial</strong> (<em>auditory</em>) while <strong>actively typing out code</strong> (kinaesthetic), will also boost your learning.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XeOemf1gpY_a6XgkXmN-6Q.jpeg" /><figcaption>Photo by Magda Ehlers: <a href="https://www.pexels.com/photo/deer-behind-grass-561870/">https://www.pexels.com/photo/deer-behind-grass-561870/</a></figcaption></figure><p><strong>Enhancing Learning through Visualisation<br></strong>Ok, even writing that subtitle made me feel a bit yoga guru but stick with me here… 🧘🏻‍♀️</p><p>Imagine you have to learn a new software architecture… <em>urgh</em>. Instead of relying solely on the <em>monotonous</em> written documentation, you could create <strong>visual diagrams</strong> that represent the architecture’s components and their relationships. 📊</p><p>The ‘simple’ act of drawing these diagrams engages your <strong>visual</strong> and <strong>spatial</strong> senses, helping you create <strong>mental models</strong> that improve your ability to retain the information. 🧠</p><blockquote>Bonus — you’ll have these visual aids as a reference, should you or a colleague require them.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BcI4qhk9hokDckTUTnJgXA.jpeg" /><figcaption>Photo by Vie Studio: <a href="https://www.pexels.com/photo/the-phrase-notice-your-senses-on-a-pin-board-7005405/">https://www.pexels.com/photo/the-phrase-notice-your-senses-on-a-pin-board-7005405/</a></figcaption></figure><h4>Conclusion</h4><p>In the world of software development, there are new developments daily. For us, this means that the ability to <strong>ingest information quickly </strong>(<em>and retain it</em>)<strong> </strong>is a real competitive advantage. Understanding and utilising multisensory integration is a<strong> super easy way to absorb information faste</strong>r, whether you work in the office or from home. So next time you have to read through some tedious documentation, try using a text-to-speech tool in addition, and be amazed at how much it helps! 💬</p><p>If you enjoyed this resource, you can help me make more (if you can!): <a href="https://buymeacoffee.com/statlfc">https://buymeacoffee.com/statlfc</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=829ff9ec703c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/rewrite-tech/stop-look-listen-utilising-your-senses-to-become-a-better-developer-%EF%B8%8F-%EF%B8%8F-829ff9ec703c">Utilising your senses to become a better developer 🖐️ 👀 🗣️</a> was originally published in <a href="https://medium.com/rewrite-tech">REWRITE TECH by Diconium</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>