IMPROVEMENT: added new action @web

This commit is contained in:
Frederico @ VilaRosa02 2025-09-18 15:42:38 +00:00
parent 902ead9855
commit 2a01cd1e28
11 changed files with 516 additions and 5 deletions

View File

@ -3,7 +3,11 @@
require_once __DIR__."/lib/index.php";
$debug_level = 0;
function LlamaCli(string $prompt, string $system = "You are a helpful assistant", array $options = []) {
function LlamaCli(string|array $prompt, string $system = "You are a helpful assistant", array $options = []) {
//
// ---- 0. OPTIONS (Default and provided) -----
//
global $debug_level;
// Get the options passed
@ -21,9 +25,20 @@ function LlamaCli(string $prompt, string $system = "You are a helpful assistant"
$context_size = $context_size ?? 4096;
// 1. Parse the prompt and resolve actions "@"
//
// ---- 1. INPUT TO LLM (DSL: adjustments needed) -----
//
// 1.1 Parse the prompt and resolve actions "@"
//if (is_array($prompt)) foreach($prompt as $i => $chunk) $prompt[$i] = ExpandFetcherCommands($chunk);
//else
$prompt = ExpandFetcherCommands($prompt);
// 1.2 Parse expanders / compressors
while(ParseExpandersIteratorsCompressors($prompt, "input",$options)) { }
if (is_array($prompt)) die("ERROR: at LLM stage, prompt is an array. Use '>(json|new-line)' compressor.");
// $llm_stdin = $prompt;
// Llama chat template
@ -43,7 +58,6 @@ function LlamaCli(string $prompt, string $system = "You are a helpful assistant"
if ($debug_file_name === false) die("Could not create temporary file\n");
$command = "$llamacpp_bin \
-m $llamacpp_model_path/$llamacpp_model \
-f $input_file_name \

View File

@ -0,0 +1,49 @@
<?php
function ParseExpandersIteratorsCompressors(&$prompt, $stage = "input",$options = []) {
global $debug_level;
$return_array = is_array($prompt);
$processed = false;
$output = [];
$prompt_as_array = is_array($prompt)?$prompt:explode("\n",$prompt);
// 1. LOOP through the lines to find COMMANDS
foreach($prompt_as_array as $line) {
// 1.1 Expand and chunk lines into arrays
if (preg_match("/^<l([0-9]+)/",trim($line),$matches)) {
$output = array_chunk($output,$matches[1]);
$output = array_map(fn($l)=>implode("\n",$l),$output);
$return_array = true;
$processed = true;
continue;
}
// 1.2 Process each chunk
if (preg_match("/^\|\s*(.+)$/",trim($line),$matches)) {
$sys_command = $matches[1];
$processed_output = [];
foreach($output as $i => $chunk) {
if ($debug_level >= 2) echo "-- DEBUG -- : Processing chunk $i of ".count($output)."\n";
$processed_output[] = LlamaCli($chunk,$sys_command,$options);
}
$output = $processed_output;
$processed = true;
$return_array = true;
continue;
}
// 1.3 Compress into text or json
if (preg_match("/^>(json|l)/",trim($line),$matches)) {
if ($matches[1] == "json") $output = json_encode($output);
if ($matches[1] == "l") $output = implode("\n",$output);
$return_array = false;
$processed = true;
continue;
}
$output[] = $line;
}
$prompt = ($return_array?$output:(is_array($output)?implode("\n",$output):$output));
return $processed;
}

View File

@ -1,2 +0,0 @@
%.action.php: %.to-be.action
~/llama.cpp/build/bin/llama-cli -m ~/llama.cpp/models/Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf -sys "User will pass a sample template of code, and you'll adapt to the following request: $(shell cat $< | tr "\n" " ")" -f action.sample.php -no-cnv 2> llama.err.log > $@

View File

@ -0,0 +1,34 @@
<?php
/**
* FETCH FILE CONTENTS ACTION
* -------------------------
* Demonstrates how to register and implement a simple action that fetches file contents.
*
* Call format:
* @fetchFileContents filename
*
* Expected output:
* The contents of the file with the specified filename
*/
// 1. Register the action with expected argument types
registerAction(
(new Action())
->setFunctionName("fetchFileContents")
->setArgumentsTypes(["filename"]) // filename
);
/**
* 2. Implement the function
*
* @param string $filename
* @return string
* @throws Exception If the file does not exist or cannot be read
*/
function fetchFileContents(string $filename): string {
try {
return file_get_contents($filename);
} catch (Exception $e) {
throw new Exception("Failed to fetch file contents: " . $e->getMessage());
}
}

View File

@ -0,0 +1 @@
implement a simple @file_contents fetcher action that expects one argument with the filename, and fills it with the file's contents

150
lib/actions/llama.err.log Normal file
View File

@ -0,0 +1,150 @@
ggml_cuda_init: GGML_CUDA_FORCE_MMQ: no
ggml_cuda_init: GGML_CUDA_FORCE_CUBLAS: no
ggml_cuda_init: found 1 CUDA devices:
Device 0: NVIDIA GeForce RTX 5060 Ti, compute capability 12.0, VMM: yes
build: 6176 (5edf1592) with cc (Ubuntu 13.3.0-6ubuntu2~24.04) 13.3.0 for x86_64-linux-gnu
main: llama backend init
main: load the model and apply lora adapter, if any
llama_model_load_from_file_impl: using device CUDA0 (NVIDIA GeForce RTX 5060 Ti) - 15713 MiB free
llama_model_loader: loaded meta data with 33 key-value pairs and 292 tensors from /home/frederico/llama.cpp/models/Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf (version GGUF V3 (latest))
llama_model_loader: Dumping metadata keys/values. Note: KV overrides do not apply in this output.
llama_model_loader: - kv 0: general.architecture str = llama
llama_model_loader: - kv 1: general.type str = model
llama_model_loader: - kv 2: general.name str = Meta Llama 3.1 8B Instruct
llama_model_loader: - kv 3: general.finetune str = Instruct
llama_model_loader: - kv 4: general.basename str = Meta-Llama-3.1
llama_model_loader: - kv 5: general.size_label str = 8B
llama_model_loader: - kv 6: general.license str = llama3.1
llama_model_loader: - kv 7: general.tags arr[str,6] = ["facebook", "meta", "pytorch", "llam...
llama_model_loader: - kv 8: general.languages arr[str,8] = ["en", "de", "fr", "it", "pt", "hi", ...
llama_model_loader: - kv 9: llama.block_count u32 = 32
llama_model_loader: - kv 10: llama.context_length u32 = 131072
llama_model_loader: - kv 11: llama.embedding_length u32 = 4096
llama_model_loader: - kv 12: llama.feed_forward_length u32 = 14336
llama_model_loader: - kv 13: llama.attention.head_count u32 = 32
llama_model_loader: - kv 14: llama.attention.head_count_kv u32 = 8
llama_model_loader: - kv 15: llama.rope.freq_base f32 = 500000.000000
llama_model_loader: - kv 16: llama.attention.layer_norm_rms_epsilon f32 = 0.000010
llama_model_loader: - kv 17: general.file_type u32 = 15
llama_model_loader: - kv 18: llama.vocab_size u32 = 128256
llama_model_loader: - kv 19: llama.rope.dimension_count u32 = 128
llama_model_loader: - kv 20: tokenizer.ggml.model str = gpt2
llama_model_loader: - kv 21: tokenizer.ggml.pre str = llama-bpe
llama_model_loader: - kv 22: tokenizer.ggml.tokens arr[str,128256] = ["!", "\"", "#", "$", "%", "&", "'", ...
llama_model_loader: - kv 23: tokenizer.ggml.token_type arr[i32,128256] = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ...
llama_model_loader: - kv 24: tokenizer.ggml.merges arr[str,280147] = ["Ġ Ġ", "Ġ ĠĠĠ", "ĠĠ ĠĠ", "...
llama_model_loader: - kv 25: tokenizer.ggml.bos_token_id u32 = 128000
llama_model_loader: - kv 26: tokenizer.ggml.eos_token_id u32 = 128009
llama_model_loader: - kv 27: tokenizer.chat_template str = {{- bos_token }}\n{%- if custom_tools ...
llama_model_loader: - kv 28: general.quantization_version u32 = 2
llama_model_loader: - kv 29: quantize.imatrix.file str = /models_out/Meta-Llama-3.1-8B-Instruc...
llama_model_loader: - kv 30: quantize.imatrix.dataset str = /training_dir/calibration_datav3.txt
llama_model_loader: - kv 31: quantize.imatrix.entries_count i32 = 224
llama_model_loader: - kv 32: quantize.imatrix.chunks_count i32 = 125
llama_model_loader: - type f32: 66 tensors
llama_model_loader: - type q4_K: 193 tensors
llama_model_loader: - type q6_K: 33 tensors
print_info: file format = GGUF V3 (latest)
print_info: file type = Q4_K - Medium
print_info: file size = 4.58 GiB (4.89 BPW)
load: printing all EOG tokens:
load: - 128001 ('<|end_of_text|>')
load: - 128008 ('<|eom_id|>')
load: - 128009 ('<|eot_id|>')
load: special tokens cache size = 256
load: token to piece cache size = 0.7999 MB
print_info: arch = llama
print_info: vocab_only = 0
print_info: n_ctx_train = 131072
print_info: n_embd = 4096
print_info: n_layer = 32
print_info: n_head = 32
print_info: n_head_kv = 8
print_info: n_rot = 128
print_info: n_swa = 0
print_info: is_swa_any = 0
print_info: n_embd_head_k = 128
print_info: n_embd_head_v = 128
print_info: n_gqa = 4
print_info: n_embd_k_gqa = 1024
print_info: n_embd_v_gqa = 1024
print_info: f_norm_eps = 0.0e+00
print_info: f_norm_rms_eps = 1.0e-05
print_info: f_clamp_kqv = 0.0e+00
print_info: f_max_alibi_bias = 0.0e+00
print_info: f_logit_scale = 0.0e+00
print_info: f_attn_scale = 0.0e+00
print_info: n_ff = 14336
print_info: n_expert = 0
print_info: n_expert_used = 0
print_info: causal attn = 1
print_info: pooling type = 0
print_info: rope type = 0
print_info: rope scaling = linear
print_info: freq_base_train = 500000.0
print_info: freq_scale_train = 1
print_info: n_ctx_orig_yarn = 131072
print_info: rope_finetuned = unknown
print_info: model type = 8B
print_info: model params = 8.03 B
print_info: general.name = Meta Llama 3.1 8B Instruct
print_info: vocab type = BPE
print_info: n_vocab = 128256
print_info: n_merges = 280147
print_info: BOS token = 128000 '<|begin_of_text|>'
print_info: EOS token = 128009 '<|eot_id|>'
print_info: EOT token = 128009 '<|eot_id|>'
print_info: EOM token = 128008 '<|eom_id|>'
print_info: LF token = 198 'Ċ'
print_info: EOG token = 128001 '<|end_of_text|>'
print_info: EOG token = 128008 '<|eom_id|>'
print_info: EOG token = 128009 '<|eot_id|>'
print_info: max token length = 256
load_tensors: loading model tensors, this can take a while... (mmap = true)
load_tensors: offloading 0 repeating layers to GPU
load_tensors: offloaded 0/33 layers to GPU
load_tensors: CPU_Mapped model buffer size = 4685.30 MiB
........................................................................................
llama_context: constructing llama_context
llama_context: n_seq_max = 1
llama_context: n_ctx = 4096
llama_context: n_ctx_per_seq = 4096
llama_context: n_batch = 2048
llama_context: n_ubatch = 512
llama_context: causal_attn = 1
llama_context: flash_attn = 0
llama_context: kv_unified = false
llama_context: freq_base = 500000.0
llama_context: freq_scale = 1
llama_context: n_ctx_per_seq (4096) < n_ctx_train (131072) -- the full capacity of the model will not be utilized
llama_context: CPU output buffer size = 0.49 MiB
llama_kv_cache_unified: CPU KV buffer size = 512.00 MiB
llama_kv_cache_unified: size = 512.00 MiB ( 4096 cells, 32 layers, 1/1 seqs), K (f16): 256.00 MiB, V (f16): 256.00 MiB
llama_context: CUDA0 compute buffer size = 669.48 MiB
llama_context: CUDA_Host compute buffer size = 20.01 MiB
llama_context: graph nodes = 1126
llama_context: graph splits = 357 (with bs=512), 1 (with bs=1)
common_init_from_params: added <|end_of_text|> logit bias = -inf
common_init_from_params: added <|eom_id|> logit bias = -inf
common_init_from_params: added <|eot_id|> logit bias = -inf
common_init_from_params: setting dry_penalty_last_n to ctx_size = 4096
common_init_from_params: warming up the model with an empty run - please wait ... (--no-warmup to disable)
main: llama threadpool init, n_threads = 8
system_info: n_threads = 8 (n_threads_batch = 8) / 16 | CUDA : ARCHS = 890 | USE_GRAPHS = 1 | PEER_MAX_BATCH_SIZE = 128 | CPU : SSE3 = 1 | SSSE3 = 1 | AVX = 1 | AVX2 = 1 | F16C = 1 | FMA = 1 | BMI2 = 1 | AVX512 = 1 | AVX512_VBMI = 1 | AVX512_VNNI = 1 | AVX512_BF16 = 1 | LLAMAFILE = 1 | OPENMP = 1 | REPACK = 1 |
sampler seed: 4251653437
sampler params:
repeat_last_n = 64, repeat_penalty = 1.000, frequency_penalty = 0.000, presence_penalty = 0.000
dry_multiplier = 0.000, dry_base = 1.750, dry_allowed_length = 2, dry_penalty_last_n = 4096
top_k = 40, top_p = 0.950, min_p = 0.050, xtc_probability = 0.000, xtc_threshold = 0.100, typical_p = 1.000, top_n_sigma = -1.000, temp = 0.800
mirostat = 0, mirostat_lr = 0.100, mirostat_ent = 5.000
sampler chain: logits -> logit-bias -> penalties -> dry -> top-n-sigma -> top-k -> typical -> top-p -> min-p -> xtc -> temp-ext -> dist
generate: n_ctx = 4096, n_batch = 2048, n_predict = -1, n_keep = 1
llama_perf_sampler_print: sampling time = 8.87 ms / 443 runs ( 0.02 ms per token, 49943.63 tokens per second)
llama_perf_context_print: load time = 657.52 ms
llama_perf_context_print: prompt eval time = 492.36 ms / 243 tokens ( 2.03 ms per token, 493.55 tokens per second)
llama_perf_context_print: eval time = 15973.53 ms / 199 runs ( 80.27 ms per token, 12.46 tokens per second)
llama_perf_context_print: total time = 16510.15 ms / 442 tokens
llama_perf_context_print: graphs reused = 192

View File

@ -0,0 +1,38 @@
<?php
/**
* ACTION: Web fetcher
* -------------------
* Call format:
* @web example.com
*
* Expected output:
* (Plain text content of the website via `lynx -dump -nolist`)
*/
// 1. Register the action with expected argument types
registerAction(
(new Action())
->setFunctionName("web")
->setArgumentsTypes(["website"]) // single argument: website URL
);
/**
* 2. Implement the function
*
* @param string $website
* @return string
*/
function web(string $website): string {
// Ensure URL has a scheme
if (!preg_match('~^https?://~i', $website)) {
$website = "https://$website";
}
// Escape for shell safety
$escaped = escapeshellarg($website);
// Run lynx and capture output
$output = shell_exec("lynx -dump -nolist $escaped 2>/dev/null | head -n 250");
return $output ?: "[error] Unable to fetch $website";
}

View File

@ -0,0 +1,31 @@
<?php require_once __DIR__."/../LlamaCli.func.php";
// TEST 07: Expander Iterator Compressor
// $out= LlamaCli_raw(
// file_get_contents(__DIR__."/test_input_data_02.american-foreign-policy.long-text.txt")
// ."\n<l50",
// "Translate the following subtitles to spanish",
// ["debug_level"=>0]
// );
// $out= LlamaCli_raw(
// file_get_contents(__DIR__."/test_input_data_01.american-foreign-policy.short-text.txt")
// ."\n<l10"
// ."\n| summarize in five words"
// ."\n>l",
// "You are a spanish translator that translates things from english.",
// ["debug_level"=>0]
// );
$out= LlamaCli_raw(
file_get_contents(__DIR__."/private_test_data.txt")
."\n<l60"
."\n| You are a legal assistant, reading a chat log of an ex-husband and wife. Count how many times the father (Frederico) visited the children (Matilda and Sebastian), after 2019. Report the dates, and total number of visits."."\n>l",
"You are a legal assistant counting the total number of times ( and dates) the father (Frederico) visited his children (Matilda and Sebastian) living with Elina.",
[
"debug_level"=>2,
"context_size"=>8192
]
);
print_r($out);

View File

@ -0,0 +1,32 @@
U.S. Foreign Policy in the Last Two Decades and the Trump Factor
Over the past twenty years, U.S. foreign policy has gone through dramatic transformations, shaped by changing global conditions, wars, economic shifts, and the personalities of the presidents in office. From the aftermath of the September 11 attacks in 2001, through the wars in Afghanistan and Iraq, to the pivot to Asia and the confrontation with rising powers like China, American global strategy has oscillated between interventionism and retrenchment. Donald Trumps presidency (20172021) marked one of the most abrupt departures from traditional U.S. foreign policy since the Second World War, but it did not exist in a vacuum—it was a reaction to, and also a catalyst for, major geopolitical shifts.
The Pre-Trump Years: 20012016
In the early 2000s, U.S. foreign policy was dominated by the “War on Terror.” George W. Bushs administration launched the invasion of Afghanistan in 2001 to topple the Taliban regime and hunt down al-Qaeda. Two years later, in 2003, the U.S. invaded Iraq, citing weapons of mass destruction (which were never found). These wars defined American foreign policy for the decade and consumed vast amounts of resources. Bush promoted a neoconservative vision of spreading democracy abroad, which often translated into military interventionism.
By the late 2000s, the costs of these wars—both financial and human—had sparked domestic fatigue. When Barack Obama took office in 2009, he promised to end “forever wars” and pursue multilateralism. His administration withdrew most U.S. combat troops from Iraq in 2011, increased the focus on Asia with the so-called “pivot to Asia,” and prioritized diplomacy, such as negotiating the 2015 Iran nuclear deal (JCPOA) and joining the Paris Climate Agreement. However, Obama also expanded drone warfare and authorized military operations in Libya, leading to criticism that his foreign policy was hesitant and inconsistent.
The Trump Doctrine: America First
Donald Trump entered office in January 2017 with the slogan “America First,” which reflected his transactional approach to foreign relations. Unlike his predecessors, he showed skepticism toward traditional alliances, international organizations, and free trade agreements. His worldview emphasized national sovereignty, economic nationalism, and the idea that U.S. allies should pay more for their own defense.
Trumps foreign policy broke with bipartisan consensus in several ways:
1. Alliances and NATO: Trump repeatedly criticized NATO allies for not meeting defense spending commitments. He suggested at times that the U.S. might not defend countries that did not contribute enough, raising doubts about the alliances credibility. This contrasted sharply with decades of American policy emphasizing collective security.
2. Middle East: Trump withdrew the U.S. from the Iran nuclear deal in 2018 and reimposed sanctions, pursuing a “maximum pressure” campaign against Tehran. His administration also brokered the Abraham Accords, which normalized relations between Israel and several Arab states, including the UAE and Bahrain. He ordered the killing of Iranian General Qasem Soleimani in 2020, escalating tensions. At the same time, Trump sought to reduce U.S. troop presence in Afghanistan and Syria, arguing against “endless wars.”
3. Asia and China: Trump adopted a confrontational approach toward China, launching a trade war that included tariffs on hundreds of billions of dollars worth of goods. His administration labeled China a strategic competitor and accused it of unfair trade practices, intellectual property theft, and human rights abuses. Relations deteriorated further over the COVID-19 pandemic, with Trump frequently blaming China for its spread.
4. Europe and Russia: Trump had a controversial relationship with Russia and President Vladimir Putin. While his administration imposed sanctions on Russia and expelled diplomats, Trump personally expressed admiration for Putin, raising concerns about his commitment to countering Russian influence. He criticized the European Union as well, calling it a “foe” in trade.
5. Multilateral Agreements: Trump withdrew the U.S. from several major international agreements and organizations, including the Paris Climate Agreement, the Trans-Pacific Partnership (TPP), and UNESCO. He reduced funding for the United Nations and pulled the U.S. out of the World Health Organization during the COVID-19 crisis.
6. Trade Policy: Trump emphasized bilateral trade deals instead of multilateral ones. He renegotiated NAFTA, replacing it with the U.S.-Mexico-Canada Agreement (USMCA). His use of tariffs was a central tool of diplomacy, applied not only to China but also to allies like Canada, Mexico, and the EU.
Impact and Legacy
Trumps foreign policy unsettled allies and foes alike. His critics argued that he weakened the international liberal order that the U.S. had helped build after 1945, eroded trust in American commitments, and left a leadership vacuum that countries like China and Russia were eager to fill. His supporters claimed that he rebalanced relationships in Americas favor, forced allies to shoulder more responsibility, and confronted China more directly than previous administrations.
At the same time, many elements of Trumps approach reflected broader trends. The skepticism toward large-scale military interventions was already growing under Obama. The bipartisan consensus on treating China as a strategic rival has largely persisted into the Biden administration. Trumps disruption accelerated these shifts but did not create them from scratch.
The Post-Trump Continuity and Contrast
Joe Bidens presidency sought to restore alliances and return to multilateralism, rejoining the Paris Agreement and emphasizing NATO solidarity. However, some Trump-era policies persisted, especially the hard line on China and the focus on domestic economic strength. The U.S. withdrawal from Afghanistan in 2021—planned under Trump and executed under Biden—illustrated the long-term fatigue with overseas military commitments. In this sense, Trumps presidency can be seen as both a break from tradition and part of an evolving trajectory of retrenchment, nationalism, and selective engagement.

View File

@ -0,0 +1,164 @@
U.S. Foreign Policy in the Last Two Decades: Continuity, Rupture, and the Trump Disruption
Introduction
From the aftermath of the Cold War in the 1990s to the present day, the United States has been the dominant global power, responsible not only for its own defense and prosperity but also for the maintenance of an international order built on rules, institutions, and alliances. Over the last twenty years, U.S. foreign policy has been shaped by four successive presidents: George W. Bush, Barack Obama, Donald Trump, and Joe Biden. Each of these leaders inherited challenges, responded in distinctive ways, and left legacies that continue to shape the world.
Among them, Donald Trumps presidency stands out as an anomaly. His “America First” approach challenged assumptions that had defined U.S. foreign policy since 1945, questioning alliances, rejecting multilateral agreements, and pursuing a transactional, nationalist vision. Yet his policies also overlapped with longer-term trends, such as skepticism toward intervention and growing rivalry with China.
This essay explores U.S. foreign policy across the last two decades, highlighting how Trump both disrupted and continued existing trajectories. It provides regional case studies (Middle East, Europe, Asia, Africa, Latin America), thematic analysis (alliances, trade, military strategy), and evaluations of continuity and change.
I. The Bush Era (20012009): The War on Terror and Neoconservative Ambition
The defining event of early 21st-century U.S. foreign policy was the September 11, 2001, terrorist attacks. Nineteen hijackers from al-Qaeda killed nearly 3,000 people on American soil, shattering the sense of invulnerability that the U.S. had enjoyed after the Cold War.
Afghanistan
Within weeks, the Bush administration launched Operation Enduring Freedom, invading Afghanistan to topple the Taliban and dismantle al-Qaeda. Initially successful, the war quickly evolved into a long-term occupation. Nation-building efforts faltered due to corruption, tribal divisions, and Pakistans ambivalent role. The U.S. remained bogged down for two decades, with troop surges under Bush, Obama, and later Trump.
Iraq
In 2003, the U.S. invaded Iraq, citing Saddam Husseins supposed weapons of mass destruction (WMDs) and ties to terrorism. Neither claim was substantiated, but the war toppled Hussein and created a power vacuum. The occupation faced insurgencies, sectarian conflict, and international criticism. The Bush Doctrine emphasized preemptive war, unilateral action, and spreading democracy—a neoconservative vision that ultimately overreached.
Global Strategy
Bush framed the world in binary terms: states were “with us or against us.” He created the Department of Homeland Security, expanded surveillance, and pursued controversial policies such as enhanced interrogation (widely seen as torture). NATO allies joined initial campaigns but grew wary of Americas unilateralism. By 2008, the wars had cost trillions, weakened U.S. credibility, and set the stage for retrenchment.
II. The Obama Era (20092017): Multilateralism and Retrenchment
Barack Obama took office promising change. He opposed the Iraq War, sought to restore diplomacy, and emphasized international cooperation.
Withdrawal from Iraq and Afghanistan
Obama withdrew combat troops from Iraq in 2011, though instability and the rise of ISIS later forced renewed engagement. In Afghanistan, he initially surged U.S. forces before committing to gradual withdrawal. His mixed legacy reflected both reluctance for endless wars and difficulty escaping them.
The Pivot to Asia
Recognizing Chinas rise, Obama announced a “pivot to Asia,” strengthening ties with allies like Japan, South Korea, and Australia. He promoted the Trans-Pacific Partnership (TPP) to counterbalance China economically. However, the pivot never fully materialized, partly due to distractions in the Middle East.
Middle East
Obama pursued diplomacy with Iran, culminating in the Joint Comprehensive Plan of Action (JCPOA) in 2015, limiting Irans nuclear program in exchange for sanctions relief. He also ordered the operation that killed Osama bin Laden in 2011. Yet his decision to intervene in Libya (2011), leading to regime collapse, drew criticism for lacking follow-through. His hesitance in Syria, particularly after Assads use of chemical weapons, led some to accuse him of weakness.
Multilateralism
Obama rejoined the Paris Climate Agreement, sought arms control with Russia (New START treaty), and promoted global institutions. His foreign policy critics accused him of “leading from behind,” while supporters praised restraint after Bushs adventurism.
III. The Trump Era (20172021): America First
Donald Trump entered office with an outsiders disdain for elite consensus. His worldview, shaped by business negotiations and nationalist rhetoric, emphasized sovereignty, economic nationalism, and skepticism toward alliances.
1. Alliances and NATO
Trump repeatedly criticized NATO allies for failing to meet the 2% defense spending target. He openly questioned whether the U.S. should defend allies who did not “pay their share.” Although his administration ultimately reinforced U.S. troop presence in some areas, the rhetoric strained relations.
2. Middle East
• Iran: Trump withdrew from the JCPOA in 2018, reimposing sanctions under a “maximum pressure” campaign. This escalated tensions, culminating in the killing of Iranian General Qasem Soleimani in January 2020.
• Israel: He moved the U.S. embassy to Jerusalem, recognized Israeli sovereignty over the Golan Heights, and brokered the Abraham Accords, normalizing relations between Israel and Arab states (UAE, Bahrain, Morocco, Sudan).
• Syria: Trump ordered strikes against Assads regime after chemical weapons attacks but also sought to reduce U.S. involvement, announcing troop withdrawals that unsettled Kurdish allies.
3. Asia and China
Trump launched a trade war with China, imposing tariffs on hundreds of billions of dollars worth of goods. He accused Beijing of intellectual property theft, unfair trade, and currency manipulation. Tensions escalated over technology (Huawei, TikTok), Hong Kong, and the South China Sea. The COVID-19 pandemic deepened hostility, with Trump blaming China for the virus.
4. North Korea
Trump broke precedent by holding summits with Kim Jong-un in Singapore (2018) and Hanoi (2019). While historic, the talks failed to achieve denuclearization. Critics called the diplomacy naïve, while supporters saw it as a bold opening.
5. Europe and Russia
Trumps relationship with Russia was controversial. While his administration sanctioned Moscow over Crimea and election interference, Trump personally expressed admiration for Putin. He criticized the European Union as a “foe” in trade, withdrew from the INF Treaty, and promoted Brexit.
6. Multilateral Agreements
Trump withdrew from:
• Paris Climate Agreement
• Trans-Pacific Partnership (TPP)
• UNESCO
• World Health Organization (during COVID-19)
He renegotiated NAFTA, replacing it with USMCA. His preference was for bilateral deals, rejecting multilateralism.
7. Africa and Latin America
Trump showed little sustained interest in Africa, focusing on counterterrorism and Chinas influence. In Latin America, he recognized Juan Guaidó as Venezuelas leader, tightened sanctions on Cuba, and pursued a hard line on migration from Central America. His rhetoric about “shithole countries” generated global outrage.
IV. The Biden Era (2021Present): Restoration and Realism
Joe Biden promised to restore alliances and global leadership. His administration rejoined the Paris Agreement, re-emphasized NATO, and sought to rebuild trust. Yet Biden also inherited Trumps populist backlash and the bipartisan consensus on China.
Afghanistan
In August 2021, Biden completed the withdrawal from Afghanistan, ending Americas longest war. Though the decision was consistent with Trumps plan, the chaotic execution drew criticism. The withdrawal symbolized U.S. fatigue with military intervention abroad.
Europe and Ukraine
Biden prioritized rebuilding NATO ties. After Russia invaded Ukraine in February 2022, his administration rallied Western allies, imposed sweeping sanctions on Moscow, and provided military aid to Kyiv. The war revitalized NATO but also strained global energy and food markets.
China
Biden maintained Trumps hard line, keeping tariffs and emphasizing strategic competition. He strengthened partnerships like the Quad (U.S., Japan, India, Australia) and AUKUS (U.S., UK, Australia). The emphasis on technology, supply chains, and military presence underscored continuity with Trumps rivalry framing.
Global Issues
Biden emphasized democracy versus autocracy as a defining struggle. He promoted climate initiatives and global health cooperation. Yet domestic polarization limited his room for maneuver.
V. Regional Case Studies
Middle East
• Continuity: Both Obama and Trump sought to reduce U.S. military footprint while maintaining influence.
• Change: Obama favored diplomacy (JCPOA); Trump favored confrontation (withdrawal and sanctions).
• Legacy: Abraham Accords may represent Trumps most enduring achievement.
Europe
• Continuity: U.S. remains central to NATO.
• Change: Trump undermined alliance confidence, while Biden restored it.
• Legacy: Russias aggression in Ukraine underscored the importance of U.S. leadership.
Asia
• Continuity: Pivot to Asia under Obama, confrontation under Trump, competition under Biden.
• Change: Trump used tariffs aggressively; Biden emphasizes coalitions.
• Legacy: U.S.China rivalry is now the defining global axis.
Africa
• Continuity: Counterterrorism and humanitarian aid remain priorities.
• Change: Trump deprioritized Africa, while China expanded influence.
• Legacy: U.S. risks losing ground in Africa to Beijing and Moscow.
Latin America
• Continuity: Migration, trade, and drug trafficking dominate.
• Change: Trump took a hard line on Cuba and Venezuela; Biden has been more cautious.
• Legacy: The region remains peripheral compared to Europe/Asia.
VI. Themes in Trumps Foreign Policy
1. Transactionalism: Viewing alliances as financial arrangements.
2. Unilateralism: Rejecting multilateral agreements.
3. Nationalism: Prioritizing sovereignty over global governance.
4. Personal Diplomacy: Engaging leaders directly, often unpredictably.
5. Disruption: Challenging taboos (North Korea summits, NATO criticism).
VII. Continuity vs. Rupture
While Trumps style was disruptive, some core shifts—skepticism of intervention, confrontation with China, fatigue with globalization—were already underway. Trump accelerated them with rhetoric and symbolic gestures. Biden has restored some norms but retained key elements, especially vis-à-vis China and trade protectionism.
Conclusion
Over the last two decades, U.S. foreign policy has evolved from Bushs interventionism to Obamas multilateral retrenchment, Trumps America First nationalism, and Bidens attempt at restoration under great-power competition. Trump was both a disruptor and a symptom: his presidency revealed deep domestic disillusionment with globalization and alliances, but also crystallized trends that are likely to persist. The world that emerges is one of selective engagement, contested leadership, and enduring rivalry with China.