teleren/devto huggingface dataset:
GPTAssistantAgent + Multi Agents
Published: 2024-01-28 15:21:07

**GPTAssistantAgent + Multi Agents**.


Group Chat

import autogen
from autogen.agentchat.contrib.gpt_assistant_agent import GPTAssistantAgent
import openai

client = openai.OpenAI()

file = client.files.create(
    file=open("2021_population.csv", "rb"),
    purpose='assistants'
)

coder_assistant = client.beta.assistants.create(
    name="Python Developer",
    instructions="You are a python developer",
    model="gpt-4-1106-preview",
    tools = [ { "type": "code_interpreter" } ],
    file_ids=[file.id]
)

analyst_assistant = client.beta.assistants.create(
    name="Data Analyst",
    instructions="You are a data analyst",
    model="gpt-4-1106-preview",
    tools = [ { "type": "code_interpreter" } ],
    file_ids=[file.id]
)

coder_llm_config = {
    "assistant_id": coder_assistant.id
}

analyst_llm_config = {
    "assistant_id": analyst_assistant.id
}

coder = GPTAssistantAgent(
    name="Coder_Assistant",
    instructions="""
    You are an expert at writing python code to solve problems. 
    Reply TERMINATE when the task is solved and there is no problem
    """,
    llm_config=coder_llm_config
)

analyst = GPTAssistantAgent(
    name="Data_Analyst",
    instructions="""
    You are a data analyst that offers insight into data.
    """,
    llm_config=analyst_llm_config,
)

user_proxy = autogen.UserProxyAgent(
    name="MervinPraison",
    code_execution_config={
        "work_dir" : "coding",
    },
    system_message="Admin"
)

groupchat = autogen.GroupChat(agents=[user_proxy, coder, analyst], messages=[], max_round=10)
manager = autogen.GroupChatManager(groupchat=groupchat)

user_proxy.initiate_chat(
    manager,
    message="""
    What is the population trend.
    Give me an overview of the data. 
    Show how you solved it with code.
    """
)
GPTAssistantAgent + Function Calling
Published: 2024-01-28 15:19:32

**GPTAssistantAgent + Function Calling**



import autogen
from autogen.agentchat.contrib.gpt_assistant_agent import GPTAssistantAgent
import openai
import yfinance as yf

client = openai.OpenAI()

def get_stock_price(symbol: str) -> float:
    stock = yf.Ticker(symbol)
    price = stock.history(period="1d")['Close'].iloc[-1]
    return price


tools_list = [{
    "type": "function",
    "function": {
        "name": "get_stock_price",
        "description": "Retrieve the latest closing price of a stock using its ticker symbol",
        "parameters": {
            "type": "object",
            "properties": {
                "symbol": {
                    "type": "string",
                    "description": "The ticker symbol of the stock"
                }
            },
            "required": ["symbol"]
        }
    }
}]

llm_config = { 
    "tools": tools_list,
}
gpt_assistant = GPTAssistantAgent(
    name="Stock Assistant",
    instructions="""
    You are a Stock Expert. 
    Reply TERMINATE when the task is solved and there is no problem
    """,
    llm_config=llm_config
)
gpt_assistant.register_function(
    function_map={
        "get_stock_price": get_stock_price,
    }
)

user_proxy = autogen.UserProxyAgent(
    name="MervinPraison",
    code_execution_config={
        "work_dir" : "coding",
    }
)

user_proxy.initiate_chat(
    gpt_assistant,
    message="""
    What is the stock price of Apple?
    """
)
GPTAssistantAgent + Code Interpreter
Published: 2024-01-28 15:18:23

**GPTAssistantAgent + Code Interpreter**




import autogen
from autogen.agentchat.contrib.gpt_assistant_agent import GPTAssistantAgent
import openai

client = openai.OpenAI()

file = client.files.create(
    file=open("2021_population.csv", "rb"),
    purpose='assistants'
)

assistant = client.beta.assistants.create(
    name="Python Developer",
    instructions="You are a python developer",
    model="gpt-4-1106-preview",
    tools = [ { "type": "code_interpreter" } ],
    file_ids=[file.id]
)

llm_config = { 
    "assistant_id": assistant.id
}

gpt_assistant = GPTAssistantAgent(
    name="Coder Assistant",
    instructions="""
    You are an expert at writing python code to solve problems. 
    Reply TERMINATE when the task is solved and there is no problem
    """,
    llm_config=llm_config
)

user_proxy = autogen.UserProxyAgent(
    name="MervinPraison",
    code_execution_config={
        "work_dir" : "coding",
    }
)

user_proxy.initiate_chat(
    gpt_assistant,
    message="""
    What is the population trend.
    Give me an overview of the data. 
    Show how you solved it with code.
    """
)
Custom GPT API Key
Published: 2024-01-28 15:14:08

**Custom GPT API Key**

{
  "openapi": "3.1.0",
  "info": {
    "title": "Get Stock Data",
    "description": "Retrieves the latest stock price for a given symbol using Basic Authentication.",
    "version": "v1.0.0"
  },
  "servers": [
    {
      "url": "https://pasttruevolume.mervinpraison.repl.co"
    }
  ],
  "paths": {
    "/stock": {
      "get": {
        "description": "Get the latest stock price for a specific symbol",
        "operationId": "GetLatestStockPrice",
        "parameters": [
          {
            "name": "symbol",
            "in": "query",
            "description": "The stock symbol to retrieve the price for",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "security": [
          {
            "basicAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "Successful response with the latest stock price",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "symbol": {
                      "type": "string"
                    },
                    "stock_price": {
                      "type": "number",
                      "format": "float"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized access due to invalid or missing API key"
          },
          "400": {
            "description": "Bad request due to missing symbol parameter"
          },
          "404": {
            "description": "No current price data available for the given symbol"
          },
          "500": {
            "description": "Internal server error"
          }
        },
        "deprecated": false
      }
    }
  },
  "components": {
    "securitySchemes": {
      "basicAuth": {
        "type": "http",
        "scheme": "basic"
      }
    },
    "schemas": {}
  }
}
"Tackling Next.js Hydration Errors: 10 Quick Tips"
Tags: nextjs, hydration, nextjsapproute, nestedhtml
Published: 2024-01-28 15:13:48

1.**HTML Nesting Consistency:**
Ensure consistent HTML nesting between server and client renders to avoid Next.js hydration errors.

2. **Use next/dynamic**:
Employ next/dynamic with ssr set to false for components loaded dynamically, ensuring smooth client-side rendering.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e54yi0u69hpstzkq5hpk.png)

3.**Leverage Lazy Importing:**
Opt for lazy importing to control client-side rendering and mitigate issues related to Next.js hydration.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tb2v6k7rx3te380pfh5k.png)
4.**Sync State Effectively:**
Keep server and client states synchronized to prevent conflicts during the hydration process.

5.**Minimize Dynamic State Changes:**
Reduce state changes during server-side rendering to minimize the risk of unexpected hydration errors.

6. **Check Browser Console:**
Regularly inspect the browser console for detailed error messages, aiding in the identification and resolution of hydration issues.

7. **Maintain Uniform Data Fetching:**
Consistently implement data fetching strategies between server and client rendering to avoid mismatches.

8. **Avoid Direct DOM Manipulation:**
Refrain from direct DOM manipulation to prevent conflicts with Next.js hydration.

9. **Stay Updated:**
Ensure you're using the latest version of Next.js, as newer releases may address hydration-related bugs.

10. **Community Engagement:**
Seek insights and share experiences on hydration errors in the Next.js community forums for collaborative problem-solving.
Get Stock Price with Basic Auth
Published: 2024-01-28 15:13:19

**Get Stock Price with Basic Auth**




from flask import Flask, request, Response
import json
import yfinance as yf

app = Flask(__name__)

API_KEY = "My_API_Key"  # Replace with your actual API key

def validate_api_key(request):
    auth_header = request.headers.get('Authorization')
    if not auth_header:
        return False

    try:
        auth_type, provided_api_key = auth_header.split(None, 1)
        if auth_type.lower() != 'basic':
            return False

        return provided_api_key == API_KEY
    except Exception:
        return False

@app.route("/")
def index():
    return "Hello world!"

@app.route('/stock', methods=['GET'])
def get_stock_data():
    if not validate_api_key(request):
        return Response(json.dumps({"error": "Invalid API key"}),
                        status=401,
                        mimetype='application/json')

    symbol = request.args.get('symbol')
    if not symbol:
        return Response(json.dumps({"error": "Symbol parameter is required"}),
                        status=400,
                        mimetype='application/json')

    stock = yf.Ticker(symbol)
    stock_price = stock.history(period="1d")['Close'].iloc[-1]

    if stock_price is None:
        return Response(json.dumps({"error": "No current price data available for the given symbol"}),
                        status=404,
                        mimetype='application/json')

    return Response(json.dumps({"symbol": symbol, "stock_price": stock_price}),
                    mimetype='application/json')

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=81)

requirements.txt

yfinance

curl -H "Authorization: Basic My_API_Key" "https://pasttruevolume.mervinpraison.repl.co/stock?symbol=AAPL"
PrivateGPT API
Published: 2024-01-28 15:12:26

**PrivateGPT API**

# Clone the repo
git clone https://github.com/imartinez/privateGPT
cd privateGPT

# Install Python 3.11
conda create -n privategpt python=3.11
conda activate privategpt

# Install dependencies
brew install poetry
poetry install --with ui,local

If needed, update settings.yaml

local: 
llm_hf_repo_id: TheBloke/Mistral-7B-Instruct-v0.1-GGUF llm_hf_model_file: mistral-7b-instruct-v0.1.Q4_K_M.gguf

then

# Download Embedding and LLM models. Takes about 4 GB
poetry run python scripts/setup

# For Mac with Metal GPU, enable it. Check Installation and Settings section to know how to enable GPU on other platforms
CMAKE_ARGS="-DLLAMA_METAL=on" pip install --force-reinstall --no-cache-dir llama-cpp-python

# Run the local server. On Mac with Metal you should see a ggml_metal_add_buffer log, stating GPU is being used
PGPT_PROFILES=local make run

# Navigate to the UI
http://localhost:8001/

API

import requests

# API endpoint
url = "http://localhost:8001/v1/chat/completions"

# Headers for the request
headers = {"Content-Type": "application/json"}

# Data payload
data = {
    "messages": [{"content": "list of happy songs from knowledge"}],
    "use_context": True,  # Set to True if needed
    "context_filter": None,  # Provide context filter if required
    "include_sources": False,  # Set to True to include sources
    "stream": False  # Set to True for streaming
}

# Making the POST request
response = requests.post(url, headers=headers, json=data)

# Extracting and printing the response
result = response.json()
print(result)
AI GPT Home Automation
Published: 2024-01-28 15:08:29

**AI GPT Home Automation**



GPT OpenAPI Schema

{
  "openapi": "3.1.0",
  "info": {
    "title": "Hue Light Control",
    "description": "Controls Philips Hue lights via a Flask API.",
    "version": "1.0.0"
  },
  "servers": [
    {
      "url": "https://example.repl.co"
    }
  ],
  "paths": {
    "/light": {
      "post": {
        "description": "Turns a specified light on or off.",
        "operationId": "controlLight",
        "requestBody": {
          "description": "Light control data",
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "light_id": {
                    "type": "integer",
                    "description": "The ID of the light to control."
                  },
                  "status": {
                    "type": "string",
                    "description": "Desired state of the light ('on' or 'off')."
                  }
                },
                "required": ["light_id", "status"]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Light control response",
            "content": {
              "text/plain": {
                "schema": {
                  "type": "string"
                }
              }
            }
          }
        }
      }
    }
  },

  "components": {
    "schemas": {}
  }
}

Public App

from flask import Flask, request

app = Flask(__name__)

@app.route('/', methods=['GET'])
def home():
  return "Hello World!"

@app.route('/light', methods=['POST'])
def control_light():
  light_data = request.json
  response = request.post('http://[PUBLIC_IP]/light', json=light_data)
  return response.text

if __name__ == '__main__':
  app.run(debug=True, host='0.0.0.0')

Local App

from flask import Flask, request
from huesdk import Hue

app = Flask(__name__)
hue = Hue(bridge_ip='[LOCAL_IP]', username='[USERNAME]')
lights = hue.get_lights()
for light in lights:
    print(f'Light ID: {light.id_}, Name: {light.name}')

@app.route('/light', methods=['POST'])
def control_light():
    light_id = request.json.get('light_id') | 1
    status = request.json.get('status')
    light = hue.get_light(id_=light_id)
    if status == 'on':
        light.on()
    else:
        light.off()
    return f'Light {light_id} turned {"on" if status == "on" else "off"}'

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')
Langchain + Assistants API
Published: 2024-01-28 15:05:52

**Langchain + Assistants API**


Basic

from langchain.agents.openai_assistant import OpenAIAssistantRunnable

assistant = OpenAIAssistantRunnable.create_assistant(
    name="langchain assistant",
    instructions="You are a personal math tutor. Write and run code to answer math questions.",
    tools=[{"type": "code_interpreter"}],
    model="gpt-4-1106-preview"
)
output = assistant.invoke({"content": "What's 10 - 4 raised to the 2.7"})

for message in output:
    print(message.content.text.value)

Langchain Function Calling

from langchain.agents.openai_assistant import OpenAIAssistantRunnable
from langchain.agents import AgentExecutor
from langchain.tools import DuckDuckGoSearchRun

tools = [DuckDuckGoSearchRun()]

assistant = OpenAIAssistantRunnable.create_assistant(
    name="langchain assistant",
    instructions="You are a personal math tutor. Write and run code to answer math questions.",
    tools=tools,
    model="gpt-4-1106-preview",
    as_agent=True,
)

agent_executor = AgentExecutor(agent=assistant, tools=tools)
output = agent_executor.invoke(
    {
        "content": 
        "What's the weather in London today divided by 2.7"
    }
)

print(f"Content: {output['content']}\nOutput: {output['output']}")
LangChain GPT4 Vision API
Published: 2024-01-28 15:05:10

**LangChain GPT4 Vision API**



Basic

from langchain.chat_models import ChatOpenAI
from langchain.schema.messages import HumanMessage, SystemMessage

chat = ChatOpenAI(model="gpt-4-vision-preview", max_tokens=256)
chat.invoke(
    [
        HumanMessage(
            content=[
                {"type": "text", "text": "What is this image showing"},
                {
                    "type": "image_url",
                    "image_url": {
                        "url": "https://raw.githubusercontent.com/langchain-ai/langchain/master/docs/static/img/langchain_stack.png",
                        "detail": "auto",
                    },
                },
            ]
        )
    ]
)

Webcam capture and analyse

import cv2
import time
import base64
from langchain.chat_models import ChatOpenAI
from langchain.schema.messages import HumanMessage, SystemMessage

def encode_image(image_path):
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode('utf-8')

cap = cv2.VideoCapture(2)

while True:
    ret, frame = cap.read()
    if not ret:
        print("Failed to grab frame")
        break

    filename = 'image.png'
    cv2.imwrite(filename, frame)

    base64_image = encode_image(filename)
    
    chat = ChatOpenAI(model="gpt-4-vision-preview", max_tokens=256)

    output = chat.invoke(
        [
            HumanMessage(
                content=[
                    {
                        "type": "text", 
                        "text": "Narrate in one line. Don't repeat. Focus on Details"
                    },
                    {
                        "type": "image_url",
                        "image_url": f"data:image/png;base64,{base64_image}"
                    },
                ]
            )
        ]
    )

    print(output)

    time.sleep(2)

cap.release()
cv2.destroyAllWindows()
How to Deploy FastAPI App or API For Free On Vercel For Free
Tags: python, api, coding, programming
Published: 2024-01-28 15:03:42

Hi 🙂🖐
In this post, I will show you how to Deploy the FastAPI App or API Free On Vercel For free

## Step 1
Install Vercel cli
from [here ](https://vercel.com/docs/cli)

## Step 2 
Login to Vercel 
[How to login](https://vercel.com/docs/cli/login)

## Create a project

```
app--
  api.py

main.py
requirements.txt
vercel.json
```

## app.py
```python

from fastapi import FastAPI

app = FastAPI()

@app.get('/')
def home():
    return {'msg': 'Welcome in my api'}
```

## main.py

```python
from dotenv import load_dotenv
import os
import uvicorn

load_dotenv()

PORT = int(os.get('PORT', 8000))
HOST = '0.0.0.0'

if __name__ == '__main__':
    uvicorn.run('app.api:app', host = HOST, port = PORT, reload = True)
```

## requirements.txt
You can generate requirements.txt using pipreqs
[https://pypi.org/project/pipreqs/](https://pypi.org/project/pipreqs/)

## vercel.json

```json
{
    "builds": [{
        "src": "app/api.py",
        "use": "@vercel/python",
        "config": { "maxLambdaSize": "15mb" }
    }],
    "routes": [
        {
            "src": "/(.*)",
            "dest": "app/api.py"
        }
    ]
}
```

## Step 3
Go to your project directory and open the cmd or terminal

type
```
vercel .
```
You will see things like this
Make the same answers
```
Vercel CLI 33.3.0
❗️  Your Project was either deleted, transferred to a new Team, or you don’t have access to it anymore.
? Set up and deploy “~\OneDrive\Desktop\python new videos\How to Deploy FastAPI App or API For Free On Vercel”? [Y/n] y
? Which scope do you want to deploy to? username
? Link to existing project? [y/N] n
? What’s your project’s name? testapi
? In which directory is your code located? ./
🔗  Linked to username/testapi (created .vercel)
🔍  Inspect: https://vercel.com/username/testapi/CdFMgqWYpMmxPi7fiPx9jxvbnSNR [2s]
✅  Production: https://testapi-k0lnh2w00-username.vercel.app [2s]
📝  Deployed to production. Run `vercel --prod` to overwrite later (https://vercel.link/2F).
💡  To change the domain or build command, go to https://vercel.com/username/testapi/settings
```
Now you can use your API 😎

**Now we're done 🤗**

**Don't forget to like and follow 🙂**
Langchain Elevenlabs Agents
Published: 2024-01-28 15:03:33

**Langchain Elevenlabs Agents**

from langchain.agents import AgentType, initialize_agent, load_tools
from langchain.llms import OpenAI
from langchain.tools import ElevenLabsText2SpeechTool

# Initialize ElevenLabsText2SpeechTool
tts = ElevenLabsText2SpeechTool()

# Initialize LLM and agent
llm = OpenAI(temperature=0)
tools = load_tools(["eleven_labs_text2speech"])
agent = initialize_agent(
    tools=tools,
    llm=llm,
    agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION,
    verbose=True
)

# Request a joke and get the path to the audio file
response = agent.run("Please provide me with an audio file containing a joke about a tiger")
print(response)

tts.play(response)
Langchain ElevenLabs
Published: 2024-01-28 15:03:00

**Langchain ElevenLabs**


Basic

from langchain.tools import ElevenLabsText2SpeechTool

text_to_speak = "Hello world! I am Mervin Praison"

tts = ElevenLabsText2SpeechTool()
speech_file = tts.run(text_to_speak)
tts.play(speech_file)

Interface

from langchain.tools import ElevenLabsText2SpeechTool
import gradio as gr

tts = ElevenLabsText2SpeechTool()

def generate_speech(text_to_speak):
    speech_file = tts.run(text_to_speak)
    return speech_file

demo = gr.Interface(
    fn=generate_speech,
    inputs=gr.Textbox(label="Enter Text"),
    outputs=gr.Audio(label="Generated Speech"),
)

if __name__ == "__main__":
    demo.launch()
AI Ollama LlamaIndex
Published: 2024-01-28 15:02:24

**AI Ollama LlamaIndex**


Basic

from llama_index.llms import Ollama

# Initialize the model
llm = Ollama(model="mistral")

response = llm.complete("Write a cover letter.")

print(response)

Basic Streaming

from llama_index.llms import Ollama

# Initialize the model
llm = Ollama(model="mistral")

response = llm.stream_complete("Write a cover letter.")

for r in response:
    print(r.delta, end="")

Chat

from llama_index.llms import Ollama
from llama_index.llms import ChatMessage

# Initialize the model
llm = Ollama(model="mistral")

messages = [
    ChatMessage(
        role="system", content="You are helpful assistant to create programs"
    ),
    ChatMessage(role="user", content="Write a python program to calculate the sum of two numbers"),
]

response = llm.chat(messages)
print(response)

Chat Streaming

from llama_index.llms import Ollama
from llama_index.llms import ChatMessage

# Initialize the model
llm = Ollama(model="mistral")

messages = [
    ChatMessage(
        role="system", content="You are helpful assistant to create programs"
    ),
    ChatMessage(role="user", content="Write a python program to calculate the sum of two numbers"),
]

response = llm.stream_chat(messages)
for r in response:
    print(r.delta, end="")