AI Agent first steps

Here I will explore AI agents technology.

agent with artificial intelligence and Development|lower


AGENTS

What agents can do?

1. Call tools (fuctions, API calls)

2. Chain of tought Cot. (LLM feature)

3. Divide user input on subtasks then run CoT.

4. Choose model most suitable for the task.

5. Run multiple LLMs in parallel and agregate their output.

6. ReAct. Run repeated LLMs calls and make decision to act (call tool, API that available).

7. Evaluation. One LLM answers user question, other LLM evaluate (critisize) output and make decision to pass or to send on additional lap with some recomendation.

8. Should have memory database to remember history of conversation and.

 

1. Which frameworks libraries we have? Smolagents (Hagging face specific), llamaindex, Langchain (popular, built on top of langgraph, open), LangGraph (low level runtime, open), Temporal, Inngest, Agno (great documentation), AutoGen and semantic-kernel (microsoft), CrewAI (open), pydantic AI (open, cisco), bee ai (closed), Google’s Agent Development Kit, haystack, LiveKit (audio/video), Microsoft Agent Framework, "Open"AI Agents (bad choice vendor closed only for "open"AI closed models), Strands Agents, Pipecat, DSPy (not agent framework but AI programming assistant), Instructor (AI app assistan), OpenDevin (coding agent), openhands, browser-use (web-automation), Vercel’s AI SDK, Google ADK, Claude Agent SDK, Manus, Deep Agents SDK

1.1 Harness: Deep Agents SDK, Claude Agent SDK, Manus

2. While I use CodeAgent with others it just gives an error tuple doesn't have startwith.

2.1. Try redefine model

model = HfApiModel(

    max_tokens=2096,

    temperature=0.5,

    model_id='Qwen/Qwen2.5-Coder-32B-Instruct',

    #model_id='deepseek-ai/DeepSeek-R1-Distill-Qwen-32B',

    #model_id='mistralai/Mistral-7B-Instruct-v0.3',

    #model_id='https://wxknx1kg971u7k1n.us-east-1.aws.endpoints.huggingface.cloud',

    #model_id="google/gemma-2-9b-it",

    custom_role_conversions=None,

    token=os.getenv('hf_token'),

)

3. While I am trying from Huggingface space to access LLM I get error Bad Request: Invalid state

3.1. The problem arrised because you didn't sent HF token in HfApiModel (look example above).

4. You can create hierarchical group of agents on basis of ManagedAgent. For example each agent on basis of different LLM.

5. To pass audio to agent. Agent has audio-to-text tool.

agent.run(

    "Why so many people in downtown of Los Angeles?",

    additional_args={"mp3_sound_file_url":'https://outleys.site/recording.mp3'}

)

6. You can use any tool from HF with your agent.

from smolagents import load_tool

model_download_tool = load_tool(

    "{your_username}/hf-model-name",

    trust_remote_code=True

)

7. Use Unity Sentis lib for AI Unity integration.

8. DeepSeek API integration.

import openai

client = openai.OpenAI(

    base_url="https://api.deepseek.com/v1",  # Check the correct API URL

    api_key="your_deepseek_api_key_here"

)

9. Where to get free LLM credits?

app.fireworks.ai/settings/users/api-keys

huggingface

9.1. How to use firefox on linux?

9.1.2. $ pip install --upgrade openai then edit file ~/.bash_profile  // doesn't work

export OPENAI_API_BASE="https://api.fireworks.ai/inference/v1"

export OPENAI_API_KEY="<YOUR_FIREWORKS_API_KEY>"

9.1.3.

import openai

client = openai.OpenAI(

api_key="my_key_here",

base_url="https://api.fireworks.ai/inference/v1"

)

10. Don't use too many tools which alike. It may cause tool overload problem.

 

OBSERVABILITY

1. Good open-source Langfuse and Langtrace (lightweight).

Langfuse

1. $ pip install langfuse opentelemetry-sdk opentelemetry-exporter-otlp openinference-instrumentation-agno

 

 

 

 

LangGraph

1. Installation

pip install -U langgraph

pip install "langchain-together>=0.1.3" "langchain-core>=0.1.23"

2. Usage example

import os

from langchain_together import ChatTogether

chat = ChatTogether(

     together_api_key=TOGETHER_API_KEY,

     model="mistralai/Mistral-7B-Instruct-v0.1",

     temperature=0.7,

     max_tokens=128

)

response = chat.invoke("Who is hasband of current US president?")

print(response.content)

 

2.1. Example $ pip install langchain

from langchain.agents import AgentType, initialize_agent, Tool

from langchain_together import ChatTogether

 

tools = [

     Tool(

         name="multiply",

         func=multiply,

         description="Multiply two numbers multiply. Input should be two numbers."

     )

 ]

 

# 1. Define tool function with SINGLE string argument

def multiply(input_str: str) -> int:

    """Multiply two numbers. Input should be 'a,b'."""

    try:

        # Parse numbers from input string

        a, b = map(float, input_str.split(","))

        return a * b

    except Exception as e:

        return f"Error: {str(e)}. Use format: '3,4'"

 

agent = initialize_agent(

    tools,

    chat,

    agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION,

    verbose=True

)

 

TOOLS

1. AgentQL can OCR pdf. Scraping web with Playwrigth with LLM query (LLM used to control playwright and understand what user want to do). You just make natural language query for LLM.

 

Request clarification tool. To create

 

OpenHands agent

1. Install

$ pip install openhands-sdk # Core SDK (openhands.sdk)

$ pip install openhands-tools  # Built-in tools (openhands.tools)

2. How to use Fireworks as llm provider. // text fireworks_ai/ before accounts/fireworks/models/ is crucial.

llm = LLM(

    model="fireworks_ai/accounts/fireworks/models/gpt-oss-120b",  # Fireworks model

    api_key="your_api_key",  # Your Fireworks API key

    base_url="https://api.fireworks.ai/inference/v1",  # Fireworks API endpoint

)

agent = Agent( llm=llm,

    tools=[ Tool(name=TerminalTool.name),

                Tool(name=FileEditorTool.name),

                Tool(name=TaskTrackerTool.name),  ],

)

cwd = os.getcwd()

conversation = Conversation(agent=agent, workspace=cwd)

conversation.send_message("Write 3 facts about the current project into FACTS.txt.")

conversation.run()

3. OpenHands has good embedded metrics:

cost = llm.metrics.accumulated_cost

cost2 = llm.metrics.accumulated_token_usage

3.1. But for observability only paid closed platforms are available.

 

 

 

 

How to pass Final Quiz of 2 smalagents unit Hugging Face Agent Course.

FIRST QUESTION

# Create a CodeAgent with DuckDuckGo search capability

from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel

agent = CodeAgent(

    tools=[DuckDuckGoSearchTool()], # Add search tool here

    model=HfApiModel(model_id='Qwen/Qwen2.5-Coder-32B-Instruct')          # Add model here

)

SECOND QUESTION

model = HfApiModel("deepseek-ai/DeepSeek-R1", provider="together", max_tokens=8096)

# Create web agent and manager agent structure

web_agent = ToolCallingAgent(

    tools=[

        DuckDuckGoSearchTool(),

        visit_webpage

    ],

    model=model,

    max_steps=10,

    name="web_agent",

    description="Browses the web to find information",

)

 

manager = CodeAgent(

    model=model,

    tools=[],

    managed_agents=[web_agent],

    additional_authorized_imports=[

        "time",

        "pandas",

        "numpy",

    ],

)

THIRD

# Set up secure code execution environment

from smolagents import CodeAgent, E2BSandbox

agent = CodeAgent(

    tools=[],

    model=model,

    sandbox=E2BSandbox(),

    additional_authorized_imports=["numpy"],

)

FORTH

# Create a tool-calling agent

from smolagents import ToolCallingAgent

agent = ToolCallingAgent(

    tools=[custom_tool], 

    model=model,

    max_steps=5,

    name="tool_agent",

    description="Executes specific tools based on input.",

    # Add configuration here

)

FIFTH

# Configure model integration

from smolagents import HfApiModel, LiteLLMModel

model = LiteLLMModel(model_id="anthropic/claude-3-sonnet", 

   temperature=0.2, 

   max_tokens=10,

   ) # Add model configuration

model2 = HfApiModel(model_id="Qwen/Qwen2.5-Coder-32B-Instruct")