Adaptability is essential to organisms’ fitness and survival. Evolutionary success depends on access to an array of behavioral choices in the face of changing environmental conditions. To navigate complex landscapes, organisms can interpret the significance of sensory stimuli, and assign context-appropriate valence, by integrating factors such as cues from their internal and external environments, and memories of previously experienced conditions, to dynamically shape neural circuits and generate ethologically relevant behaviors. In this thesis, I explore the cellular and molecular mechanisms that shape the carbon dioxide (CO2) circuit in the free-living nematode, Caenorhabditis elegans. CO2 is a complex sensory cue that can signify the presence of fruitful or dangerous surroundings. As a result, C. elegans can display a variety of different behaviors in response to CO2, from robust attraction to robust avoidance. Although sensory signaling of the CO2-responsive BAG neurons has been extensively characterized, how BAG communicates with postsynaptic interneurons, and how the CO2 signal is propagated through the nervous system to generate a context-appropriate behavior is unknown. First, we have found that neuromodulatory state and environmental oxygen (O2) levels converge on the CO2 circuit via the URX sensory neurons. The lab-derived N2 C. elegans strain expresses high levels of NPR-1 neuropeptide receptor, which inhibits URX and results in CO2 avoidance, regardless of environmental O2. In the C. elegans wild isolate “Hawaii”, loss of npr-1 leads to modulation of URX by environmental O2, and results in CO2 avoidance at low O2, and loss of CO2-evoked behavior at high O2. Second, we present a new circuit motif that demonstrates how divergent responses to a single sensory input, CO2, can arise from an identical set of sensory and interneuron connections. We show that C. elegans exhibit an experience-dependent behavioral valence switch in response to CO2. While animals raised at ambient CO2 are repelled by CO2, animals raised in a high CO2 environment are attracted to CO2. Whether CO2 is attractive or repulsive is determined by the coordinated activity of specialized valence-encoding interneurons, AIY, RIG, and RIA, whose responses are subject to context-dependent modulation. An additional interneuron pair, AIZ, regulates behavioral sensitivity regardless of valence. Glutamatergic and neuropeptidergic signaling mediate both CO2 avoidance and attraction, and different neuropeptides play distinct roles in regulating valence and sensitivity. Our results elucidate a microcircuit motif whereby a fixed set of neurons are leveraged to generate alternative outputs in response to a single chemosensory input.