Basic Coding for AI
Essential programming skills to enhance your AI agent development capabilities
Why Learn to Code for AI Development?
While no-code platforms offer impressive capabilities, understanding basic coding unlocks a new level of customisation, control, and capability in AI agent development. Even minimal coding skills can dramatically expand what you can accomplish.
Key Insight
You don't need to become a full-stack developer to leverage code in AI development. A focused approach on specific AI-relevant coding skills yields the highest return on your learning investment.
The No-Code to Code Spectrum
Where You Should Focus Based on Your Goals:
| Skill Level | Capabilities | Best For |
|---|---|---|
| Pure No-Code | Using platforms as designed with existing integrations | Quick implementation, standard use cases |
| Light Coding | Basic API calls, simple scripts, minor customisations | Extending platform capabilities, custom integrations |
| Moderate Coding | Custom tools, data processing, advanced integrations | Specialised agents, unique workflows, data manipulation |
| Advanced Coding | Custom models, complex systems, full-stack applications | Novel applications, research, enterprise solutions |
This section focuses on the "Light to Moderate" coding skills that provide the highest ROI for most AI agent developers. These skills allow you to extend no-code platforms while avoiding the steep learning curve of advanced AI development.
Python: The Essential Language for AI
Python has emerged as the dominant language for AI development due to its readability, extensive libraries, and strong community support. Even basic Python skills can significantly enhance your AI capabilities.
Why Python for AI?
- Readability: Clean syntax that's easy to learn and understand
- Libraries: Extensive ecosystem of AI and data science packages
- Integration: Excellent support for API calls and web services
- Community: Vast resources, tutorials, and support available
- Versatility: Used across the AI stack from data processing to model deployment
Python Fundamentals for AI Development
Focus on these core Python concepts that are most relevant to AI agent development:
1. Variables and Data Types
# Basic variable assignment
user_query = "Tell me about AI agents"
max_tokens = 500
temperature = 0.7
include_sources = True
# Common data types
# Strings - for text
model_name = "gpt-4"
# Integers and floats - for numerical values
max_results = 5
confidence_threshold = 0.85
# Booleans - for true/false values
is_verified = False
# Lists - for ordered collections
search_results = ["result1", "result2", "result3"]
# Dictionaries - for key-value pairs (extremely important for API work)
parameters = {
"model": "gpt-4",
"temperature": 0.7,
"max_tokens": 500,
"top_p": 1.0
}
2. Control Structures
# Conditional logic
if confidence_score > 0.9:
response = "I'm highly confident that..."
elif confidence_score > 0.7:
response = "I believe that..."
else:
response = "I'm not sure, but..."
# Loops for iteration
for result in search_results:
print(f"Processing result: {result}")
# While loops for condition-based iteration
while api_calls < max_attempts and not success:
try:
response = make_api_call()
success = True
except Exception as e:
api_calls += 1
print(f"Attempt {api_calls} failed: {e}")
3. Functions
# Basic function definition
def generate_response(prompt, model="gpt-3.5-turbo", temperature=0.7):
"""
Generate a response using an LLM.
Args:
prompt (str): The input prompt
model (str): The model to use
temperature (float): Controls randomness (0.0-1.0)
Returns:
str: The generated response
"""
# Function implementation here
response = "This is a dummy response."
return response
# Using the function
answer = generate_response(
prompt="Explain AI agents simply",
temperature=0.5
)
Python Learning Shortcut
Instead of taking a comprehensive Python course, focus on learning through AI-specific examples. Start with simple scripts that call AI APIs, then gradually add complexity as you build practical projects.
Recommended approach: Learn enough Python to understand and modify existing AI code examples, then expand your knowledge as needed for specific projects.
API Integration: The Core Skill
The most valuable coding skill for AI agent development is the ability to integrate with APIs (Application Programming Interfaces). This allows your agents to communicate with AI models and other services.
Understanding API Basics
Key API Concepts:
- Endpoints: URLs that accept requests for specific services
- HTTP Methods: GET, POST, PUT, DELETE for different operations
- Headers: Metadata for requests, including authentication
- Request Body: Data sent to the API (often in JSON format)
- Response: Data returned by the API (typically JSON)
- Status Codes: Numeric codes indicating success or failure (200 OK, 404 Not Found, etc.)
Making API Calls in Python
The requests library is the standard for making HTTP requests in Python:
import requests
import os # Need to import os for getenv
# Assume api_key is defined or fetched securely, e.g., from environment variables
api_key = os.getenv("YOUR_API_KEY", "default_key_if_not_set")
# Basic GET request
try:
response = requests.get('https://api.example.com/data')
response.raise_for_status() # Raises an HTTPError for bad responses (4XX or 5XX)
data = response.json()
print(data)
except requests.exceptions.RequestException as e:
print(f"Request failed: {e}")
# POST request with JSON data
headers = {
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json'
}
data = {
'prompt': 'Explain AI agents',
'max_tokens': 500,
'temperature': 0.7
}
try:
response = requests.post(
'https://api.example.com/generate',
headers=headers,
json=data
)
response.raise_for_status() # Check for HTTP errors
result = response.json()
# Safely access nested keys
generated_text = result.get('choices', [{}])[0].get('text', 'No text found')
print(generated_text)
except requests.exceptions.RequestException as e:
print(f"Request failed: {e}")
except (KeyError, IndexError) as e:
print(f"Failed to parse response: {e}")
Working with OpenAI's API
The OpenAI API is one of the most commonly used for AI agent development. Here's how to use it with the official Python library:
import openai
import os
from dotenv import load_dotenv
# Load API key from .env file (best practice for security)
load_dotenv()
openai.api_key = os.getenv("OPENAI_API_KEY")
def get_completion(prompt, model="gpt-3.5-turbo", temperature=0.7):
"""
Get a completion from the OpenAI API
"""
try:
messages = [{"role": "user", "content": prompt}]
response = openai.ChatCompletion.create(
model=model,
messages=messages,
temperature=temperature,
)
return response.choices[0].message["content"]
except openai.error.OpenAIError as e:
print(f"OpenAI API error: {e}")
return None
except Exception as e:
print(f"An unexpected error occurred: {e}")
return None
# Example usage
prompt = "Explain how AI agents work in simple terms."
response = get_completion(prompt)
if response:
print(response)
# More complex conversation with system message
def chat_completion(messages, model="gpt-3.5-turbo", temperature=0.7):
"""
Get a chat completion from the OpenAI API
"""
try:
response = openai.ChatCompletion.create(
model=model,
messages=messages,
temperature=temperature,
)
return response.choices[0].message["content"]
except openai.error.OpenAIError as e:
print(f"OpenAI API error: {e}")
return None
except Exception as e:
print(f"An unexpected error occurred: {e}")
return None
# Example chat usage
messages = [
{"role": "system", "content": "You are a helpful AI assistant specialised in explaining technical concepts simply."},
{"role": "user", "content": "What is the difference between supervised and unsupervised learning?"}
]
response = chat_completion(messages)
if response:
print(response)
# Add the response to the conversation history for follow-up
messages.append({"role": "assistant", "content": response})
# Example follow-up question
messages.append({"role": "user", "content": "Give me an example of unsupervised learning."})
follow_up_response = chat_completion(messages)
if follow_up_response:
print(follow_up_response)
Security Alert: API Keys
Never hardcode API keys directly into your scripts. Use environment variables (like shown with os.getenv() and dotenv) or secure key management systems.
Working with Data (JSON)
AI development heavily involves exchanging data with APIs, typically in JSON (JavaScript Object Notation) format. Python's built-in json library makes this easy.
Key JSON Concepts
- Objects: Key-value pairs (like Python dictionaries)
- Arrays: Ordered lists (like Python lists)
- Values: Strings, numbers, booleans, objects, or arrays
Parsing and Generating JSON in Python
import json
# Example JSON string received from an API
json_string = '{
"agent_name": "Research Assistant",
"status": "active",
"capabilities": ["web_search", "summarization", "email_report"],
"parameters": {
"max_search_results": 10,
"summary_length": "concise"
}
}'
# Parse JSON string into a Python dictionary
data = json.loads(json_string)
print(f"Agent Name: {data['agent_name']}")
print(f"Capabilities: {data['capabilities']}")
print(f"Summary Length: {data['parameters']['summary_length']}")
# Modify the data
data['status'] = "inactive"
data['parameters']['summary_length'] = "detailed"
# Convert Python dictionary back into a JSON string
updated_json_string = json.dumps(data, indent=4) # indent for pretty printing
print("\nUpdated JSON:")
print(updated_json_string)
Handling Potential Errors
When accessing data from JSON, always anticipate that keys might be missing or have unexpected types. Use .get() for safer dictionary access and include error handling (try-except blocks).
# Safer dictionary access
agent_name = data.get('agent_name', 'Unknown Agent') # Provides default value
try:
# Access potentially missing key
report_format = data['settings']['report_format']
except KeyError:
print("Report format setting not found, using default.")
report_format = "standard"
except TypeError:
print("Settings format incorrect, using default report format.")
report_format = "standard"
Essential Python Libraries for AI
Beyond built-in features, specific Python libraries greatly simplify common AI tasks:
| Library | Primary Use | Why It's Useful |
|---|---|---|
requests |
Making HTTP requests (API calls) | Simplifies interacting with web services |
openai |
Interacting with OpenAI APIs | Official library, handles complexity |
dotenv |
Managing environment variables | Securely handling API keys and configuration |
json |
Working with JSON data | Standard format for API communication |
pandas |
Data manipulation and analysis | Handling structured data, useful for RAG |
BeautifulSoup4 / Scrapy |
Web scraping | Extracting information from websites |
For basic agent development extending no-code platforms, focusing on requests, openai, dotenv, and json is often sufficient.
Practical Example: A Simple Python Agent Tool
Let's create a simple Python script that could be used as a custom tool within an agent workflow (e.g., called by a no-code platform that supports custom code execution).
Objective: Currency Converter Tool
A tool that takes an amount, a source currency, and a target currency, then returns the converted amount using a free currency conversion API.
import requests
import json
def convert_currency(amount, from_currency, to_currency):
"""
Converts an amount from one currency to another using a free API.
Note: Uses exchangerate-api.com which offers a free tier.
Requires sign-up for an API key.
Replace YOUR_API_KEY with your actual key or use environment variable.
"""
# In a real application, get API key securely (e.g., os.getenv)
api_key = "YOUR_API_KEY"
base_url = f"https://v6.exchangerate-api.com/v6/{api_key}/latest/{from_currency}"
try:
response = requests.get(base_url)
response.raise_for_status() # Check for HTTP errors
data = response.json()
if data['result'] == 'success':
conversion_rate = data['conversion_rates'].get(to_currency)
if conversion_rate:
converted_amount = amount * conversion_rate
return {
"success": True,
"from_currency": from_currency,
"to_currency": to_currency,
"original_amount": amount,
"converted_amount": round(converted_amount, 2),
"rate": conversion_rate
}
else:
return {"success": False, "error": f"Target currency '{to_currency}' not found."}
else:
# Handle API-specific errors if documentation provides details
error_type = data.get('error-type', 'Unknown API error')
return {"success": False, "error": f"API Error: {error_type}"}
except requests.exceptions.RequestException as e:
return {"success": False, "error": f"Network error: {e}"}
except json.JSONDecodeError:
return {"success": False, "error": "Failed to decode API response."}
except Exception as e:
# Catch any other unexpected errors
return {"success": False, "error": f"An unexpected error occurred: {e}"}
# Example usage:
result = convert_currency(100, "USD", "GBP")
print(json.dumps(result, indent=4))
result_error = convert_currency(100, "USD", "XYZ") # Invalid currency
print(json.dumps(result_error, indent=4))
# This script can be saved as a .py file and potentially called by an agent.
# Input parameters (amount, from_currency, to_currency) would typically be
# passed to the script, and the JSON output would be returned to the agent flow.
Integration with No-Code Platforms
Platforms like Zapier, Make.com, or even some specialized agent builders allow executing custom Python or JavaScript code. You could deploy this function (e.g., as a serverless function) and have your no-code agent call its endpoint, or paste the script directly if the platform supports it.
Next Steps: Understanding LLMs
With a foundation in basic coding and API interaction, you're ready to dive deeper into the core technology powering modern AI agents: Large Language Models (LLMs).
Key Takeaways from This Section:
- Basic Python coding significantly enhances AI agent development capabilities
- Focus on Python fundamentals, API integration (using
requests), and JSON handling - Securely manage API keys using environment variables
- Key libraries include
requests,openai,dotenv, andjson - Simple Python scripts can act as custom tools within larger agent workflows
The next section explores LLM essentials, providing the knowledge needed to effectively leverage language models in your agents, whether built with code or no-code platforms.
Continue to LLM Essentials →