Categories
AI

Fine Tuning GPT 3.5 16K

Fine Tuning

from openai import OpenAI
import time

client = OpenAI()

# Create file for fine-tuning
file = client.files.create(
    file=open("mervinpraison.jsonl", "rb"),
    purpose="fine-tune"
)

print(f"File ID: {file.id}, File Status: {file.status}")

# Create a fine-tuning job
job = client.fine_tuning.jobs.create(
    training_file=file.id,
    model="gpt-3.5-turbo-1106"
)

print(f"Job ID: {job.id}, Job Status: {job.status}")

while True:
    time.sleep(10)  
    job = client.fine_tuning.jobs.retrieve(job.id)
    if job.status == 'succeeded':
        model_name = f"ft-{job.model}:suffix:{job.id}"
        print(f"Job ID: {job.id}, Final Job Status: {job.status}")
        print(f"Model Name: {model_name}")
        break
    elif job.status == 'failed':
        print(f"Job ID: {job.id}, Final Job Status: {job.status}")
        break
    else:
        print(f"Checking... Job ID: {job.id}, Current Job Status: {job.status}")

Using Fine tuned Model

from openai import OpenAI
client = OpenAI()

response = client.chat.completions.create(
    model="ft:gpt-3.5-turbo-1106:mervin-praison::8QUpHZjq",
    messages=[
        {"role": "system", "content": "Mervin Praison is a factual chatbot with a sense of humor."},
        {"role": "user", "content": "How far is the sun?"},
    ]
)

print(response.choices[0].message.content)

Using Fine tuned Model with UI

from openai import OpenAI
import gradio as gr
client = OpenAI()

def chat_with_model(user_input):
    response = client.chat.completions.create(
        model="ft:gpt-3.5-turbo-1106:mervin-praison::8QVebIU4",
        messages=[
            {"role": "system", "content": "Mervin Praison is a factual chatbot with a sense of humor."},
            {"role": "user", "content": user_input},
        ]
    )
    return response.choices[0].message.content

chatbot = gr.Interface(
    fn=chat_with_model,
    inputs=gr.Textbox(lines=2, placeholder="Enter your question here...", label="Question"),
    outputs="text",
    title="Chat with Mervin Praison Chatbot",
    description="This is a chatbot with a sense of humor. Ask any question!"
)

chatbot.launch()

mervinpraison.jsonl

{"messages": [{"role": "system", "content": "Mervin Praison is a factual chatbot with a sense of humor."}, {"role": "user", "content": "What's the tallest mountain in the world?"}, {"role": "assistant", "content": "Mount Everest, it's so high it's almost touching the sky!"}]}
{"messages": [{"role": "system", "content": "Mervin Praison is a factual chatbot with a sense of humor."}, {"role": "user", "content": "What is the speed of light?"}, {"role": "assistant", "content": "It's about 299,792 kilometers per second. Faster than any of us on a Monday morning!"}]}
{"messages": [{"role": "system", "content": "Mervin Praison is a factual chatbot with a sense of humor."}, {"role": "user", "content": "Who discovered gravity?"}, {"role": "assistant", "content": "That would be Sir Isaac Newton. An apple a day keeps the gravity at play!"}]}
{"messages": [{"role": "system", "content": "Mervin Praison is a factual chatbot with a sense of humor."}, {"role": "user", "content": "How many planets are in the Solar System?"}, {"role": "assistant", "content": "Eight planets. Sorry Pluto, you're still not on the list!"}]}
{"messages": [{"role": "system", "content": "Mervin Praison is a factual chatbot with a sense of humor."}, {"role": "user", "content": "What is the largest ocean?"}, {"role": "assistant", "content": "The Pacific Ocean. It's so big, you can't see the other side from here!"}]}
{"messages": [{"role": "system", "content": "Mervin Praison is a factual chatbot with a sense of humor."}, {"role": "user", "content": "What's the smallest country in the world?"}, {"role": "assistant", "content": "Vatican City. It's so small, you might miss it if you blink!"}]}
{"messages": [{"role": "system", "content": "Mervin Praison is a factual chatbot with a sense of humor."}, {"role": "user", "content": "Who is the author of 'Harry Potter'?"}, {"role": "assistant", "content": "J.K. Rowling. She cast a spell and created a whole new world!"}]}
{"messages": [{"role": "system", "content": "Mervin Praison is a factual chatbot with a sense of humor."}, {"role": "user", "content": "What is the boiling point of water?"}, {"role": "assistant", "content": "100 degrees Celsius. It's hot enough to make a cup of tea, or two!"}]}
{"messages": [{"role": "system", "content": "Mervin Praison is a factual chatbot with a sense of humor."}, {"role": "user", "content": "What's the longest river in the world?"}, {"role": "assistant", "content": "The Nile River. It's so long, it could be a marathon route!"}]}
{"messages": [{"role": "system", "content": "Mervin Praison is a factual chatbot with a sense of humor."}, {"role": "user", "content": "Who was the first person on the moon?"}, {"role": "assistant", "content": "Neil Armstrong. He took a small step for man and a giant leap for mankind (and chatbots!)" }]}
Categories
AI

AutoGen Chess Agent

import chess, chess.svg, autogen, sys, os
from collections import defaultdict
from typing import Any, Dict, List, Optional, Union

sys_msg = """You are an AI-powered chess board agent. 
Translate natural language into legal UCI moves. 
Reply only with a UCI move string."""

class RefereeAgent(autogen.AssistantAgent):
    board: chess.Board
    correct_move_messages: Dict[autogen.Agent, List[Dict]]

    def __init__(self, board: chess.Board):
        super().__init__( name="RefereeAgent", system_message=sys_msg, llm_config={"temperature": 0.0}, max_consecutive_auto_reply=10, )
        self.register_reply(autogen.ConversableAgent, RefereeAgent._generate_board_reply)
        self.board = board
        self.correct_move_messages = defaultdict(list)

    def _generate_board_reply( self, messages: Optional[List[Dict]] = None, sender: Optional[autogen.Agent] = None, config: Optional[Any] = None, ) -> Union[str, Dict, None]:
        message = messages[-1]
        reply = self.generate_reply(self.correct_move_messages[sender] + [message], sender, exclude=[RefereeAgent._generate_board_reply])
        uci_move = reply if isinstance(reply, str) else str(reply["content"])
        try:
            self.board.push_uci(uci_move)
        except ValueError as e:
            return True, f"Error: {e}"
        else:
            print("Current board state:")
            print(self.board)
            self.correct_move_messages[sender].extend([message, self._message_to_dict(uci_move)])
            self.correct_move_messages[sender][-1]["role"] = "assistant"
            
            # Call the function to save the SVG
            self.save_board_state_as_svg()

            return True, uci_move
    
    def save_board_state_as_svg(self):
        moves_dir = 'moves'
        if not os.path.exists(moves_dir):
            os.makedirs(moves_dir)
        move_count = len(self.board.move_stack)
        svg_filename = os.path.join(moves_dir, f'move_{move_count}.svg')
        svg_output = chess.svg.board(self.board)
        with open(svg_filename, 'w') as file:
            file.write(svg_output)

sys_msg_tmpl = """Your name is {name} and you are a chess player.
You are playing against {opponent_name}.
You are playing as {color}.
You communicate your move using universal chess interface language.
You also chit-chat with your opponent when you communicate to light up the mood.
You should ensure both you and the opponent are making legal moves.
Do not apologise for making illegal moves."""

class ChessPlayerAgent(autogen.AssistantAgent):
    def __init__( self, color: str, referee_agent: RefereeAgent, max_turns: int, **kwargs, ):
        if color not in ["white", "black"]:
            raise ValueError(f"color must be either white or black, but got {color}")
        opponent_color = "black" if color == "white" else "white"
        name = f"Player {color}"
        opponent_name = f"Player {opponent_color}"
        sys_msg = sys_msg_tmpl.format( name=name, opponent_name=opponent_name, color=color, )
        super().__init__(name=name,system_message=sys_msg,max_consecutive_auto_reply=max_turns,**kwargs,)
        self.register_reply(ChessPlayerAgent, ChessPlayerAgent._generate_reply_for_player, config=referee_agent)        
        self.register_reply(RefereeAgent, ChessPlayerAgent._generate_reply_for_board, config=referee_agent.board)
        self.update_max_consecutive_auto_reply(referee_agent.max_consecutive_auto_reply(), referee_agent)

    def _generate_reply_for_player( self, messages: Optional[List[Dict]] = None, sender: Optional[autogen.Agent] = None, config: Optional[RefereeAgent] = None, ) -> Union[str, Dict, None]:
        referee_agent = config
        board_state_msg = [{"role": "system", "content": f"Current board:\n{referee_agent.board}"}]
        # propose a reply which will be sent to the board agent for verification.
        
        message = self.generate_reply(messages + board_state_msg, sender, exclude=[ChessPlayerAgent._generate_reply_for_player])
        if message is None:
            return True, None
        # converse with the board until a legal move is made or max allowed retries.
        self.initiate_chat(referee_agent, clear_history=False, message=message, silent=self.human_input_mode == "NEVER")
        last_message = self._oai_messages[referee_agent][-1]
        if last_message["role"] == "assistant":
            sys.stdout.write(f"{self.name}: I yield.\n")
            return True, None
        return True, self._oai_messages[referee_agent][-2]

    def _generate_reply_for_board( self, messages: Optional[List[Dict]] = None, sender: Optional[autogen.Agent] = None, config: Optional[chess.Board] = None, ) -> Union[str, Dict, None]:
        board = config
        board_state_msg = [{"role": "system", "content": f"Current board:\n{board}"}]
        last_message = messages[-1]
        if last_message["content"].startswith("Error"):
            last_message["role"] = "system"
            return True, self.generate_reply(messages + board_state_msg, sender, exclude=[ChessPlayerAgent._generate_reply_for_board])
        else:
            return True, None

"""## Construct Agents"""

max_turn = 2

board = chess.Board()
referee_agent = RefereeAgent(board=board)
player_black = ChessPlayerAgent(
    color="black",
    referee_agent=referee_agent,
    max_turns=max_turn,
    llm_config={"temperature": 0.0, "seed": 48},
)
player_white = ChessPlayerAgent(
    color="white",
    referee_agent=referee_agent,
    max_turns=max_turn,
    llm_config={"temperature": 0.0, "seed": 49},
)

"""## Start Game"""

player_black.initiate_chat(player_white, message="Your turn.")

Same code with few extras

import chess
import chess.svg
import autogen
import sys
import os

from collections import defaultdict
from typing import Any, Dict, List, Optional, Union

sys_msg = """You are an AI-powered chess board agent.
You translate the user's natural language input into legal UCI moves.
You should only reply with a UCI move string extracted from the user's input."""

class UmpireAgent(autogen.AssistantAgent):
    board: chess.Board
    correct_move_messages: Dict[autogen.Agent, List[Dict]]

    def __init__(self, board: chess.Board):
        super().__init__(
            name="UmpireAgent",
            system_message=sys_msg,
            llm_config={"temperature": 0.0},
            max_consecutive_auto_reply=10,
        )
        self.register_reply(autogen.ConversableAgent, UmpireAgent._generate_board_reply)
        self.board = board
        self.correct_move_messages = defaultdict(list)

    def _generate_board_reply(
        self,
        messages: Optional[List[Dict]] = None,
        sender: Optional[autogen.Agent] = None,
        config: Optional[Any] = None,
    ) -> Union[str, Dict, None]:
        message = messages[-1]
        reply = self.generate_reply(self.correct_move_messages[sender] + [message], sender, exclude=[UmpireAgent._generate_board_reply])
        uci_move = reply if isinstance(reply, str) else str(reply["content"])
        try:
            self.board.push_uci(uci_move)
        except ValueError as e:
            return True, f"Error: {e}"
        else:
            print("Current board state:")
            print(self.board)
            self.correct_move_messages[sender].extend([message, self._message_to_dict(uci_move)])
            self.correct_move_messages[sender][-1]["role"] = "assistant"
            
            # Save the SVG to a file in 'moves' folder
            moves_dir = 'moves'
            if not os.path.exists(moves_dir):
                os.makedirs(moves_dir)
            move_count = len(self.board.move_stack)
            svg_filename = os.path.join(moves_dir, f'move_{move_count}.svg')
            svg_output = chess.svg.board(self.board)
            with open(svg_filename, 'w') as file:
                file.write(svg_output)

            return True, uci_move

sys_msg_tmpl = """Your name is {name} and you are a chess player.
You are playing against {opponent_name}.
You are playing as {color}.
You communicate your move using universal chess interface language.
You also chit-chat with your opponent when you communicate a move to light up the mood.
You should ensure both you and the opponent are making legal moves.
Do not apologize for making illegal moves."""

class ChessPlayerAgent(autogen.AssistantAgent):

    def __init__(
        self,
        color: str,
        umpire_agent: UmpireAgent,
        max_turns: int,
        **kwargs,
    ):
        if color not in ["white", "black"]:
            raise ValueError(f"color must be either white or black, but got {color}")
        opponent_color = "black" if color == "white" else "white"
        name = f"Player {color}"
        opponent_name = f"Player {opponent_color}"
        sys_msg = sys_msg_tmpl.format(
            name=name,
            opponent_name=opponent_name,
            color=color,
        )
        super().__init__(
            name=name,
            system_message=sys_msg,
            max_consecutive_auto_reply=max_turns,
            **kwargs,
        )
        self.register_reply(UmpireAgent, ChessPlayerAgent._generate_reply_for_board, config=umpire_agent.board)
        self.register_reply(ChessPlayerAgent, ChessPlayerAgent._generate_reply_for_player, config=umpire_agent)
        self.update_max_consecutive_auto_reply(umpire_agent.max_consecutive_auto_reply(), umpire_agent)

    def _generate_reply_for_board(
        self,
        messages: Optional[List[Dict]] = None,
        sender: Optional[autogen.Agent] = None,
        config: Optional[chess.Board] = None,
    ) -> Union[str, Dict, None]:
        board = config
        # add a system message about the current state of the board.
        board_state_msg = [{"role": "system", "content": f"Current board:\n{board}"}]
        last_message = messages[-1]
        if last_message["content"].startswith("Error"):
            # try again
            last_message["role"] = "system"
            return True, self.generate_reply(messages + board_state_msg, sender, exclude=[ChessPlayerAgent._generate_reply_for_board])
        else:
            return True, None

    def _generate_reply_for_player(
        self,
        messages: Optional[List[Dict]] = None,
        sender: Optional[autogen.Agent] = None,
        config: Optional[UmpireAgent] = None,
    ) -> Union[str, Dict, None]:
        umpire_agent = config
        # add a system message about the current state of the board.
        board_state_msg = [{"role": "system", "content": f"Current board:\n{umpire_agent.board}"}]
        # propose a reply which will be sent to the board agent for verification.
        message = self.generate_reply(messages + board_state_msg, sender, exclude=[ChessPlayerAgent._generate_reply_for_player])
        if message is None:
            return True, None
        # converse with the board until a legal move is made or max allowed retries.
        # change silent to False to see that conversation.
        self.initiate_chat(umpire_agent, clear_history=False, message=message, silent=self.human_input_mode == "NEVER")
        # last message sent by the board agent
        last_message = self._oai_messages[umpire_agent][-1]
        if last_message["role"] == "assistant":
            # didn't make a legal move after a limit times of retries.
            sys.stdout.write(f"{self.name}: I yield.\n")
            return True, None
        return True, self._oai_messages[umpire_agent][-2]

"""## Construct Agents"""

max_turn = 2

board = chess.Board()
umpire_agent = UmpireAgent(board=board)
player_black = ChessPlayerAgent(
    color="black",
    umpire_agent=umpire_agent,
    max_turns=max_turn,
    llm_config={"temperature": 0.5, "cache_seed": 4},
)
player_white = ChessPlayerAgent(
    color="white",
    umpire_agent=umpire_agent,
    max_turns=max_turn,
    llm_config={"temperature": 0.5, "cache_seed": 5},
)

"""## Start Game"""

player_black.initiate_chat(player_white, message="Your turn.")

Categories
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="")
Categories
AI

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()
Categories
AI

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)
Categories
AI

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()
Categories
AI

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']}")
Categories
AI

GPT Assistants API Parallel Function Calling

export OPENAI_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxx
export GNEWS_API_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxx
import openai
import time
import json
from yfinance import Ticker
import requests, os

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

GNEWS_API_KEY = os.getenv('GNEWS_API_KEY')

def get_latest_company_news(company_name):
    url = f"https://gnews.io/api/v4/search?q={company_name}&token={GNEWS_API_KEY}&lang=en&sortBy=publishedAt"
    response = requests.get(url)
    if response.status_code == 200:
        return response.json()['articles']
    else:
        return []
    
def usd_to_gbp(usd_amount):
    url = "https://api.exchangerate-api.com/v4/latest/USD"
    try:
        response = requests.get(url)
        data = response.json()
        gbp_rate = data['rates']['GBP']
        return usd_amount * gbp_rate
    except Exception as e:
        return f"Error: {e}"

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"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "get_latest_company_news",
            "description": "Fetches the latest news articles related to a specified company",
            "parameters": {
                "type": "object",
                "properties": {
                    "company_name": {
                        "type": "string",
                        "description": "The name of the company"
                    }
                },
                "required": ["company_name"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "usd_to_gbp",
            "description": "Converts an amount in USD to GBP using the current exchange rate",
            "parameters": {
                "type": "object",
                "properties": {
                    "usd_amount": {
                        "type": "number",
                        "description": "The amount in USD to be converted"
                    }
                },
                "required": ["usd_amount"]
            }
        }
    }
]

# Initialize the client
client = openai.OpenAI()

# Step 1: Create an Assistant
assistant = client.beta.assistants.create(
    name="Data Analyst Assistant",
    instructions="You are a personal Data Analyst Assistant",
    model="gpt-4-1106-preview",
    tools=tools_list,
)

# Step 2: Create a Thread
thread = client.beta.threads.create()

# Step 3: Add a Message to a Thread
message = client.beta.threads.messages.create(
    thread_id=thread.id,
    role="user",
    content="""Can you please provide me stock price,
    stock price in GBP,
    and the latest company news of Apple?
    """
)

# Step 4: Run the Assistant
run = client.beta.threads.runs.create(
    thread_id=thread.id,
    assistant_id=assistant.id,
    instructions="Please address the user as Mervin Praison."
)

print(run.model_dump_json(indent=4))

# Define a dispatch table
function_dispatch_table = {
    "get_stock_price": get_stock_price,
    "get_latest_company_news": get_latest_company_news,
    "usd_to_gbp": usd_to_gbp
}

while True:
    # Wait for 5 seconds
    time.sleep(5)

    # Retrieve the run status
    run_status = client.beta.threads.runs.retrieve(
        thread_id=thread.id,
        run_id=run.id
    )
    print(run_status.model_dump_json(indent=4))

    # If run is completed, get messages
    if run_status.status == 'completed':
        messages = client.beta.threads.messages.list(
            thread_id=thread.id
        )

        # Loop through messages and print content based on role
        for msg in messages.data:
            role = msg.role
            content = msg.content[0].text.value
            print(f"{role.capitalize()}: {content}")
        break
    elif run_status.status == 'requires_action':
        print("Requires action")
        required_actions = run_status.required_action.submit_tool_outputs.model_dump()
        print(required_actions)
        tools_output = []

        for action in required_actions["tool_calls"]:
            func_name = action["function"]["name"]
            arguments = json.loads(action["function"]["arguments"])

            func = function_dispatch_table.get(func_name)
            if func:
                result = func(**arguments)
                # Ensure the output is a JSON string
                output = json.dumps(result) if not isinstance(result, str) else result
                tools_output.append({
                    "tool_call_id": action["id"],
                    "output": output
                })
            else:
                print(f"Function {func_name} not found")

        # Submit the tool outputs to Assistant API
        client.beta.threads.runs.submit_tool_outputs(
            thread_id=thread.id,
            run_id=run.id,
            tool_outputs=tools_output
        )


    else:
        print("Waiting for the Assistant to process...")
        time.sleep(5)
Categories
AI

AutoGen TeachableAgent

Install

pip install "pyautogen[teachable]"

Prerequisite

export OPENAI_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxx

Code

from autogen import UserProxyAgent, config_list_from_json
from autogen.agentchat.contrib.teachable_agent import TeachableAgent

# Create TeachableAgent
teachable_agent = TeachableAgent(
    name="teachableagent",
    teach_config={
        "reset_db": False,
        "path_to_db_dir": "teachable_agent_db"
    }
)

# Create UserProxyAgent
user = UserProxyAgent("user", human_input_mode="ALWAYS")

# Chat with TeachableAgent
teachable_agent.initiate_chat(user, message="Hi, I'm a teachable user assistant! What's on your mind?")

# Update the database
teachable_agent.learn_from_user_feedback()
teachable_agent.close_db()
Categories
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')